I seem to be having a timing issue and userForm.valid is not set on initial refresh of my screen. By the time I see the page, userForm.valid is set to true. but in the mean time, errors are dumped to the chrome development console. How do I wait for this code to complete before rendering the screen? Running Angular: 11.2.12
user-add.component.ts
userForm: FormGroup;
. . .
ngOnInit(): void {
this.route.params.subscribe(params => {
this.getUserForm();
});
}
private getUserForm(): void {
this.userForm = new FormGroup({
id: new FormControl(this.user.id),
active: new FormControl(this.user.active),
name: new FormControl(this.user.name, [
Validators.required,
Validators.maxLength(50)
]),
email: new FormControl(this.user.email, [
Validators.required,
Validators.email,
Validators.maxLength(50),
Validators.pattern("(?!.*[\\ |#|$|%|^|\\*|\\?]).*")
]),
homeBranches: new FormControl(this.userHomeBranches)
});
}
HTML:
<div>
<p> userForm.valid </p>
<pre>{{ userForm.valid }} </pre>
</div>
Console.log: core.js:6210 ERROR TypeError: Cannot read properties of undefined (reading 'valid')
Once the screen refresh is complete: userForm.valid true
CodePudding user response:
Change
userForm.valid
to
userForm?.valid
The ?
operator indicates that the object might be undefined.
You can also use *ngIf
to make sure the form is set
<div *ngIf="userForm">
<p> userForm?.valid </p>
<pre>{{ userForm?.valid }} </pre>
</div>