Angular does not propagate validation to custom form control ng-select

In my Angular 9 application, I am utilizing Reactive Forms with a Custom Form Control.

I have enclosed my ng-select control within the Custom Form Control.

However, I am facing an issue with validation. Even though I have set the formControl to be required, according to the documentation, the ng-invalid css class should be automatically applied to ng-select. But with custom form control, this is not working as expected. The css class is not being set, although the wrapper class is. Can you advise if I am overlooking something or if this is related to a library problem?

Feel free to check out the stackblitz example: https://stackblitz.com/edit/angular-rmvttg-ex63ka?file=src/forms-single-select-example.component.html&fbclid=IwAR2robtd_15khTVhmW59lLhn21HOHl_yYTrCWKaPRmfUt1QVvUn3n8V4Vjo

Answer №1

One issue with Angular is that it applies the control status CSS classes to your custom control instead of the ng-select within it.

To solve this, you can inject ngControl and check for control.control.invalid and control.control.touched.

constructor(private injector:Injector){}
ngOnInit()
{
   this.control = this.injector.get(NgControl);
}

You can then use something like

  <ng-select #mySelect  [ngClass]="{'ng-invalid':control?.control.invalid,
                                    'ng-touched':control?.control.touched}"
   ....>

Another approach is to query the parent's class. By creating a getter like

get parentClass()
{
  const match = /class=\"(.*?)\">/.exec(this.element.nativeElement.parentElement.innerHTML);
  return match[0].split('"')[1]
}

constructor(private element:ElementRef){}

You can use

<ng-select #mySelect  [ngClass]="parentClass" 
  ...>

For a simpler solution, wrapping ng-select doesn't require creating a custom form control, just a basic component with an @Input

@Input()control:any

Then you can use it like

    <mycontrol [control]="someForm.get('someControl')"></mycontrol>

Check out how easy it is in this StackBlitz example

Answer №2

To solve this issue, you can pass the FormGroup as a prop to your subcomponent using Input and then assign it to the ng-select:

<mycontrol formControlName="someControl" [parentFormGroup]="someForm" ></mycontrol>

Subcomponent:

export class MyControlComponent implements ControlValueAccessor {

  @Input() parentFormGroup: FormGroup;
...

Template:

<ng-select #mySelect
           [formGroup]="parentFormGroup"
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

The vertical scrolling functionality of the MUI DataGrid in Safari may occasionally fail to work

Utilizing the <Box> component from MUI core and the <DataGrid> component from MUIX, along with some other components, I have created a data grid that has the following appearance: https://i.sstatic.net/Gc8sP.png When the number of rows exceed ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

How can you effectively declare a computed getter in MobX that aggregates an observable list?

Within my project, I have a class hierarchy consisting of projects, task lists, and tasks. Each array is marked as @observable. Now, I am looking to create a "@computed get allTasks" function within the project class that aggregates all tasks from all task ...

Issue: "The argument provided must be a specific string, not a string or an array of strings."

Currently, I am tackling a Vue project that incorporates TypeScript and axios for handling API requests. While working on the Reset Password component, the resetPassword function within the auth.ts file appears as follows: resetPassword(password1: string, ...

Is it possible to create a QR Code using Ionic 5?

Is there a way to generate QR Codes in Ionic 5? I attempted it, but keep receiving an error stating that the qrcode element is not recognized. Here is my code: qrcode.html <ion-item> <ion-input type="text" placeholder="My QR d ...

Struggling with setting up the onChange function in a Next.js application

After successfully writing and testing the code here, I encountered an error preventing me from building it. Please review the code for any issues. I am attempting to set onChange to handle user input in a text field. Currently using onChange={onChange}, ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

Implementing data binding for arrays of inputs in Angular

Can anyone provide assistance with this code snippet and explain why it is not functioning as expected? I am trying to generate input fields from a string array and bind each input value to its corresponding element in the array. It seems like a common tas ...

Tips for passing the same value to two components using vuejs $emit

Can someone help with typing in Main, where the value can also be Test World? You can view a sample here >>> Sample The issue I'm facing is that when a user adds an item to the cart, the cart shows one more than it should. I've tried t ...

The default value for the ReturnType<typeof setInterval> in both the browser and node environments

I have a question about setting the initial value for the intervalTimer in an Interval that I need to save. The type is ReturnType<typeof setInterval>. interface Data { intervalTimer: ReturnType<typeof setInterval> } var data : Data = { ...

Testing for target instanceof window.Window in jest involves writing a test case using the expect keyword

I am currently working on a function in TypeScript that handles scrolling. Here is the code snippet with type definitions for reference... function scroll(target: HTMLElement, {posX, posY}: ScrollPosition): void { if (target instanceof window.Window) ...

Angular failing to render data in user interface

Exploring the concept of CRUD Operations, I am attempting to implement basic CRUD operations using Angular for the front end and Web API for the back end. The API is quite straightforward, returning a simple JSON structure as shown below: [ { "stud ...

Tomcat fails to identify cpho.html and hhpnz.html files as index.html files

I have a challenge running two applications within one Angular project. My objective is to host these apps on a Tomcat server. The issue arises when I attempt to build the project and deploy the dist folder to Tomcat. It seems that the cpho.html and hhpnz. ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Refresh a doughnut chart in real-time using NG2Charts

Currently, I am in the process of developing a macronutrient calculator as part of a project. The idea is to have a form where users can input values, and a corresponding doughnut chart will display with initial values set at 0. However, upon clicking the ...

Angular allows cross-origin requests with Access-Control-Allow-Origin

Hi, I am facing an issue with the update function in my app. Whenever I try to update, it shows me the following error message: Failed to load http:// localhost:8080/../update: Response to preflight request doesn't pass access control check: No &apo ...

Errors may occur when utilizing TypeScript with the Context Provider API in React

I am in the process of developing a theme changer feature and I want to save the color chosen by the user in the context. However, when I try to pass data to the value prop of the Context.Provider, I encounter an error message TS2739: Type 'Readonly&l ...

Unable to bind to property as it is not recognized as a valid attribute of the selector component

I have a situation where I need to pass a variable from one component to another using @input. Here is my parent component : @Component({ selector: 'aze', templateUrl: './aze.component.html', styleUrls: [('./aze.compo ...

Cookie-setting isn't functioning properly on Opera and Firefox browsers, but it is working correctly on Postman when using Express

After spending an entire day researching, I have yet to find a solution to my problem despite trying everything possible. I suspect that the issue lies with the browser's security policy because my server and client are both running on different loca ...