我收到此错误:
ERROR TypeError: Cannot read property 'invalid' of undefined
它指向这里:/image/XPMkw.jpg
我做了一些调整,例如注释掉选项,它指出 选择元素itemBrand:
<select id="itemBrand" name="itemBrand" formControlName="itemBrand" class="form-control btn-sm brand" (change)="changeBrand($event)" required>
所以我认为 formControl 验证器对我的选择元素有问题。但我无法修复它。
这是使用表单生成器初始化表单:
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>
最佳答案
Try
*ngIf="itemBrand?.invalid"
instead of*ngIf="itemBrand.invalid"
for a safe condition check.
关于javascript - 解决错误类型错误 : Cannot read property 'invalid' of undefined for Select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472893/