I'm doing a web application in Angular 6 and I'm using Reactive Forms. I have a Form Group with an array and I am setting the values in ngOnInit. I have a custom validator to know if the field called id is unique.
officesFormGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.officesFormGroup = this.fb.group({
offices: this.fb.array([], Validators.required)
});
}
ngOnInit() {
this.setOffices();
}
setOffices() {
const control = this.officesForm;
this.company.offices.forEach((office, index) => {
control.push(this.fb.group({
id: office.id,
name: office.name,
address: office.address,
services: this.fb.array([], Validators.required)
}, {validator: this.officeValidator.bind(this)}));
}
officeValidator(control: AbstractControl) {
const id = control.get('id').value;
if (id !== null && id !== '') {
const offices: Office[] = this.officesForm.value;
const isIdUnique = offices.map(office => office.id)
.some(value => value === id);
if (isIdUnique) {
control.get('id').setErrors({unavailable: true});
} else {
control.get('id').setErrors(null);
}
}
}
get officesForm() {
return this.officesFormGroup.get('offices') as FormArray;
}
To add a new office to the array:
addOffice() {
const office = this.fb.group({
id: [null, Validators.required],
name: [null, Validators.required],
address: [null, Validators.required],
services: this.fb.array([], Validators.required)
}, {validator: this.officeValidator.bind(this)});
this.officesForm.push(office);
}
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'.
When the page is loaded for the first time, the field called id appears red, like it has errors, which is wrong. It should check for unique if the user adds another office and writed something in the id field.
My goal is, if the user adds a new office or try to edit the id of an existing office, check if the id is unique, I mean, if no other office has the same id.