1

I have an Angular Component that is a customizable "select" where user can search for results and select the desired value like this:

enter image description here

The component stores the selected value inside it to be read by it's parent component.

The page that will use this component use reactive forms to validate the fields, is there a way to customize the component to use the reactive forms of the parent component? Maybe my Component needs to extend the AbstractControl class, would it be right?

Since this is a custom field, i can't use formControlName on child, I have to built a custom validation logic on the component to validate whether any value has been selected because it's not a simple input or select field.

The structure is kind like this.

<div formArrayName="myFormArray" *ngFor="let contact of contacts">
   <app-select-search ...> //this is my custom component I want to validate using reactive forms with custom validation rule
   </app-select-search>
</div>

I have read lots of articles that shows how to use reactive form on child components to validate simple fields passing the parent form to the child component as an @Input but I couldn't find any example using a user custom defined rule like this

Note: This child component will be loaded dynamically so the parent component will have a Form Array to load it.

1
  • I believe the simplest thing is to pass a FormControl into <app-select-search> as an input variable, then add a custom ValidatorFn to the FormControl: angular.io/guide/form-validation#custom-validators. Both the parent and child will have a reference to the same FormControl object. If you create an example in stackblitz I can fill in the blanks. Commented Mar 15, 2022 at 23:14

1 Answer 1

1

While I was writing this question I came with the idea of extending my component to the AbstractControl class. Then I started searching for this and found that this is exactly what I need. Follow a detailed article about this subject for anyone that faces the same problem as me: https://blog.angular-university.io/angular-custom-form-controls/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.