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 to execute a function in a child component that is declared in the parent component using Angular

Is anyone able to help me with an issue I am facing in my Angular project? I have two components, 'app' and 'child'. Within the child component, I have a button that calls a function defined in the app component. However, this setup is ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

What causes Enum[Enum.member] to be undefined in the TypeScript playground on codepen.io?

My intention was to test out some type settings on TypeScript playground at codepen.io, but I encountered an unexpected issue: enum Order { Asc = 'asc', Desc = 'desc' } console.log(Order[Order.Asc]); // undefined in codepen.io ...

How to Position Logo in the Center of MUI AppBar in React

I've been struggling to center align the logo in the AppBar. I can't seem to get the logo to be centered both vertically and horizontally on its own. Here is my code from AppBar.tsx: import * as React from 'react'; import { styled, useT ...

What type of event does the Input element in material-ui v1 listen for?

I'm currently grappling with material-ui v1 as I search for the appropriate event type for input elements. Take a look at the code snippet below: <Select value={this.numberOfTickets} onChange={this.setNumberOfTickets}> .... Here is the impleme ...

You cannot assign an array of 'Contact' objects to a single 'Contact' parameter

During the development process, I encountered an error while trying to add a new contact. The error message states: Error: src/app/contacts/contacts.component.ts:32:28 - error TS2345: Argument of type 'Contact[]' is not assignable to parameter o ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

What is the best way to declare a collection of objects in TypeScript?

Need assistance with TypeScript - Can anyone help? I'm having trouble deciphering the error message in relation to the code snippet below. My goal is to create an array of objects, but it doesn't seem to be working as expected. interface FieldC ...

Retrieve the value of a variable to access an object property dynamically in React Native using TypeScript

As I attempted to create dynamic styles for this component, my goal was to determine the styles based on a string passed in as a property. Here is the code snippet: export type MyComponentProps = { styleName: string; } const MyComponent = (props: MyComp ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...

Develop a component library for Angular 2 without incorporating inline styles

I recently came across an interesting article about developing an Angular 2 component library that utilizes inline styles. Is there a method to create a library in Angular 2 without relying on inline styles? I also stumbled upon another resource, but it d ...

Using Typescript with Styled-Components and Styled-System: Unable to find a matching overload for this function call

Encountering the infamous "No overload matches this call" error when using a combination of Typescript, Styled-Components, and Styled-System. I've come across solutions that suggest passing a generic type/interface to the styled component, like the o ...

Changes are made to the Angular template-driven form after certain controls have been added or removed

Within a fieldset, there exists a flexible number of 'select' drop down lists, accompanied by a button after each one (except the last one) to remove it. Upon selecting an option from the last select control, a new select control is dynamically a ...

Is it possible to use Firebase auth.user in order to retrieve the signed-in user directly?

As I develop a webapp with NextJS v13.4 and firebase as my backend using the firebase web modular api, I came across a statement in the documentation: "The recommended way to get the current user is by setting an observer on the Auth object." ...

Leverage the extended properties of Express.js's Request's generic arguments

I am currently working on extending the Request type to include a property that relies on the request body. However, I am facing an issue where the generic in catchAsync is not being correctly applied and always defaults to any instead of the specified gen ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

Angular material tree with nested branches broken and in disarray

I'm facing a challenge with the UI issue of expanding trees on the last node, as it always creates excessive lines from the nodes, similar to the image below. I attempted to adjust the left border height but saw no change at all. Does anyone have any ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

There are no route parameters defined

Within my user template file, I have a tab control implemented as shown below: <nav md-tab-nav-bar> <a class="tab-label" md-tab-link [routerLink]="'following'" routerLinkActive #following="routerLinkActive" [acti ...