I am new to Angular and I need to mark two form fields as touched and invalid by default in one of my components. My ngOnInit() currently looks like this:
ngOnInit() {
this.serviceData.registrationData.search.forms.markAllAsTouched()
setTimeout(() =>
this.serviceData.registrationData.search.forms.controls.id1.setErrors({ invalid: true })
this.serviceData.registrationData.search.forms.controls.id2.setErrors({ invalid: true })
})
}
If I only include
this.serviceData.registrationData.search.forms.controls.id1.setErrors({ invalid: true })
inside setTimeout() the program is working as it should. If however, I also include the code line for id2, I get an Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
and the field is not being marked as invalid. The part of the code from my template which is being referenced in the error message looks like this:
<div class="message-error"
*ngIf="serviceData.registrationData.search.forms.controls.id2.invalid"
>
<p>{{'REQUEST.SEARCH.symbolsInId2'}}</p>
</div>
What can I do so that this error is fixed and both of my field are marked as invalid? Any help is greatly appreciated.
MosMp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.