angular – 无法读取null的’required’属性

前端之家收集整理的这篇文章主要介绍了angular – 无法读取null的’required’属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在模板中,我有一个表单,其中一部分与渲染课程列表有关:

<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 ERROR TypeError: Cannot read property
required’ of null
at Object.eval [as updateDirectives] (CourseComponent.html:20)

你能帮我找出导致这个错误的原因吗?

Boot Code 3.3.7已安装在VS代码中.

解决方法

错误并不总是存在,所以你必须像这样定义它:

<div class="alert alert-danger" *ngIf="courseCategory.touched && courseCategory.errors?.required">

安全运算符“?”

猜你在找的Angularjs相关文章