I'm building a form array correctly via this way:
this.items.forEach(element => {
(<FormArray>this.myFormFixtures.get('fixtures')).push(this.fBuilder.group({
id: [element.id],
name: [element.name, Validators.required],
description: [element.description],
startDateTime: this.buildTimeDetails(element.startDateTime),
venueId: [element.venueId, Validators.required],
participants: this.buildParticipants(element.participants)
}));
});
this.myFormFixtures.valueChanges
.subscribe(formData => this.checkFixturesFormValidity(formData));
The "Participants" key is generated into an array with 2 ids with null value like so:
[
{id: null},
{id: null}
]
By default the 2 ids are optional. But I want to set both participant ids formControlNames to be required should one acquire a value.
So far my "checkFixturesFormValidity" function is looking like this, but for some reason the validation isn't being set:
checkFixturesFormValidity(formData)
{
console.log(formData);
const control = <FormArray>this.myFormFixtures.controls['fixtures'];
for (let i = 0; i < control.length; i++) {
const participantsControl = (<FormArray>this.myFormFixtures.controls['fixtures']).at(i).get('participants') as FormArray;
if ((((<any>this.myFormFixtures.controls['fixtures']).at(i).controls['participants'].at(0).get('id').value) != null) || (((<any>this.myFormFixtures.controls['fixtures']).at(i).controls['participants'].at(1).get('id').value) != null))
{
(<any>this.myFormFixtures.controls['fixtures']).at(i).controls['participants'].at(0).get('id').setValidators([Validators.required]);
(<any>this.myFormFixtures.controls['fixtures']).at(i).controls['participants'].at(1).get('id').setValidators([Validators.required]);
}
}
}
updateValueAndValidity(). If it does not help, please create a plunker which demonstrates the issue..subscribe(formData => this.checkFixturesFormValidity(formData))checkFixturesFormValidity()is called everytime something happens in form values, and since you are usingupdateValueAndValidity()in that, "changes happen", which means subscribe is fired again and so it goes on, until browser crashes ;) You should consider a simplechangeevent for the field instead.updateValueAndValiditywill solve your issue. As a sidenote, even if this is a matter of opinion, I have come to rely on events instead of usingvalueChangesunless I have some specific reason. With events you have tighter control on what is fired and when. When using valueChanges you cannot control it as tight, and performance wise this can become heavy. Even just on component initializationvalueChangeswill be fired x amount of times, which is usually totally unnecessary :)