在模板驱动的表单中,我得到以下错误。
ERROR TypeError: Cannot read property 'invalid' of undefined
我不知道为什么会出现这种情况,如何解决这个问题?
app.component.html:
<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="categoryName">Category Name:</label>
<input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>
<div *ngIf="f.submitted && categoryName.invalid" class="invalid-feedback">
<div *ngIf="categoryName.errors.required">
Category Name is required
</div>
</div>
<div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">
Category Name must be at least 5 characters long.
</div>
</div>
</form>
app.component.ts:
cate: any = {};
onSubmit() {
alert(this.cate.categoryName);
}
在你的模板中。
categoryName.invalid
但我没看到任何地方的categoryName被设置成什么。
你可以像这样 "修复 "它
categoryName?.invalid
请注意 #categoryname
和categoryName是不一样的(小写与大写 "n")。