Hi I am having an issue with a validator as it is not getting called.
Currently I am having an Angular 5
component with a formgroup
defined in it. The formgroup
has a form array element. Each element in the formgroup
array is of type FormGroup
. I have written a validator
named duplicateClientNameValidator
. however when i edit the form the validator
is not getting called. so following is my component ts file
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { duplicateClientNameValidator } from '../../shared';
@Component({
selector: 'pc-account-service-provider-clients',
templateUrl: './account-service-provider-clients.component.html',
styleUrls: ['./account-service-provider-clients.component.scss']
})
export class AccountServiceProviderClientsComponent implements OnInit {
formGroup: FormGroup;
constructor( private fb: FormBuilder) { }
ngOnInit() {
this.formGroup = this.fb.group({
aliases: this.fb.array([])
},[duplicateClientNameValidator('aliases')]);
}
get aliases() {
return this.formGroup.get('aliases') as FormArray;
}
addAlias() {
const formGroupNew: FormGroup = new FormGroup( {
id: new FormControl( { value:'', disabled:false}),
name: new FormControl({ value:'', disabled:false},[Validators.required, Validators.maxLength(50)]),
companyNumber: new FormControl({ value:'', disabled:false},Validators.maxLength(20))
}
);
this.aliases.push(formGroupNew);
}
removeItem( index :number){
this.aliases.removeAt(index);
}
handleSubmit() {}
get cancelLink(): string {
return '/dashboard';
}
}
The following is the definition of my validator
funtion duplicateClientNameValidator
export function duplicateClientNameValidator( serviceProviderClientControlArrayName: string):ValidationErrors | null {
return (control: FormGroup): ValidationErrors | null => {
const aliases:FormArray = <FormArray>control.get(serviceProviderClientControlArrayName);
for(const formGrp of aliases.controls ) {
const frmGroup: FormGroup = <FormGroup> formGrp;
console.log(frmGroup.get('name').value);
}
return null;
};
}
The following is the snap of the UI . I can use the +
icon to add new items into the formgroup
and after editing all the field i am expecting the duplicateClientNameValidator
is called . however it is not getting called . really appreciate any help
I have declared the formgroup incorrectly . once i changed as below it started to work fine.
this.formGroup = this.fb.group({
aliases: this.fb.array([])
},{validator: [duplicateClientNameValidator('aliases')]});