Reputation: 46
I am getting this error:
ERROR TypeError: Cannot read property 'invalid' of undefined
And it is pointing here: https://i.sstatic.net/XPMkw.jpg
I did some tweaking such as commenting out the options and it pointed to the select element itemBrand:
<select id="itemBrand" name="itemBrand" formControlName="itemBrand" class="form-control btn-sm brand" (change)="changeBrand($event)" required>
So I am thinking that the formControl validator is having an issue with my select element. But I cannot fix it.
Here is the initialization of the form using form builder:
typescript:
ngOnInit() {
this.getBrands();
this.itemAddForm = this.fb.group({
itemName: ['', Validators.required],
itemBrand: ['Select a Brand', Validators.required],
// ....
});
}
html:
<form class="form-horizontal" [formGroup]="itemAddForm" (ngSubmit)="onSubmit()">
<fieldset>
<div class="form-group">
<label class="col-md-3 control-label" for="itemName">Item Name</label>
<div class="col-md-6">
<input id="itemName" name="itemName" formControlName="itemName" class="form-control input-md" required
type="text">
</div>
<div *ngIf="itemAddForm.get('itemName').errors && itemAddForm.get('itemName').touched">
<p class="error-message text-danger"><span class="error-icon text-danger">!
</span>{{itemAddForm.get('itemName').errors.msg || 'Please enter an item name.'}}</p>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="itemBrand">Brand</label>
<div class="col-md-6">
<div class="input-group mb-3">
<select id="itemBrand" name="itemBrand" formControlName="itemBrand"
class="form-control btn-sm brand" (change)="changeBrand($event)" required>
<!-- <option [value]="" disabled>Select a brand</option> -->
<option *ngFor="let brand of brands" [value]="brand?.brand">{{ brand?.brand }}</option>
</select>
<div *ngIf="itemBrand.invalid">
Select a brand.
</div>
</div>
</div>
</fieldset>
</form>
Upvotes: 0
Views: 144
Reputation: 38683
Try
*ngIf="itemBrand?.invalid"
instead of*ngIf="itemBrand.invalid"
for a safe condition check.
Upvotes: 1