Reputation: 444
I have been stuck at this silly angular 5 reactive forms error which i am not able to get rid of. While adding the validation message block in html, I am getting the error
"Cannot read property 'invalid' of undefined"
which is weird as there is a form control element with the same name and I am able to access the value of that feild. Below is the code
HTML file
<form [formGroup]='signUpForm'>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" formControlName='password'>
<div *ngIf="password.invalid && (password.dirty || password.touched)"
class="alert alert-danger">
<div *ngIf="password.errors.required">
Name is required.
</div>
</div>
</div>
</div>
</div>
</form>
ts code
signUpForm: FormGroup;
this.signUpForm = new FormGroup({
username:new FormControl('',Validators.required),
email:new FormControl('',[Validators.required]),
password:new FormControl('',Validators.required),
})
Please help. Thanks in advance
Upvotes: 0
Views: 286
Reputation: 12960
Where do you initialize the form?? If you do it in ngOnInit()
, you should not be facing that problem.
If you are initializing the form under any other custom method of yours then you can use something like:
Use the safe navigation operator ?
. This checks whether the first operator results to true or not. When the view is rendered it might be possible that the control is not initialized yet. So suppose if the component variable password
is not defined when your view is rendered and you try to access a property invalid
of password
(which is undefined), you will get the error you get now..
for example:
<div *ngIf="password?.invalid && (password?.dirty || password?.touched)" class="alert alert-danger">
So your actual view could be like:
<form [formGroup]='signUpForm'>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" formControlName='password'>
<div *ngIf="password?.invalid && (password?.dirty || password?.touched)" class="alert alert-danger">
<div *ngIf="password?.errors?.required">
Name is required.
</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation: 509
Try This Code.
<div *ngIf="signUpForm.controls['password'].invalid && (signUpForm.controls['password'].dirty || signUpForm.controls['password'].touched)"
class="alert alert-danger">
<div *ngIf="signUpForm.get('password').hasError('required')">
Name is required.
</div>
</div>
Upvotes: 1