在模板中,我有一个表单,其中一部分与呈现课程列表有关:
<form #f="ngForm" (ngSubmit)="submit(f)">
<div class="form-group">
<label for="courseCategory"> Category </label>
<select required ngModel name="courseCategory" #courseCategory="ngModel" id="courseCategory" class="form-control">
<option value=""></option>
<option *ngFor="let category of categories" [value]="category.id"> // line 16
{{category.name}}
</option>
</select>
<div class="alert alert-danger" *ngIf="courseCategory.touched && courseCategory.errors.required">
Course category is required
</div>
</div>
</form>
在浏览器中,当我选择一个类别并按TAB键(移出下拉列表)时,在控制台上出现此错误:
CourseComponent.html:16错误TypeError:无法读取Object.eval的null属性'required'[作为updateDirectives](CourseComponent.html:20)
您能帮我找出造成此错误的原因吗?
VS Code中已经安装了Bootstrap 3.3.7。
错误并不总是存在的,因此您必须这样定义它:
<div class="alert alert-danger" *ngIf="courseCategory.touched && courseCategory.errors?.required">
与安全操作员“?”
为什么我们使用安全运算符“?”
@konda对不起,我刚刚看到您发表评论。正如David所解释的,错误并不总是存在。因此,我们应该告诉Angular仅在遇到错误时才渲染此div。如果我们不使用安全运算符,Angular会尝试渲染不存在的内容。这导致崩溃。