【问题标题】:Cannot read property 'required' of null无法读取 null 的属性“必需”
【发布时间】:2018-05-17 16:10:03
【问题描述】:

在模板中,我有一个表单,其中一部分与渲染课程列表有关:

<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 错误类型错误:无法读取属性 “必需”为空 在 Object.eval [as updateDirectives] (CourseComponent.html:20)

您能帮我找出导致此错误的原因吗?

Bootstrap 3.3.7 已安装在 VS Code 中。

【问题讨论】:

    标签: angular forms


    【解决方案1】:

    错误不会一直存在,所以你必须这样定义:

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

    使用安全运算符“?”

    【讨论】:

    • 为什么我们使用安全运算符“?”
    • @konda 对不起,我刚刚看到你的评论。正如大卫解释的那样,错误并不总是存在。所以我们应该告诉 Angular 只有在出现错误时才渲染这个 div。如果我们不使用安全操作符,Angular 会尝试渲染不存在的东西。这会导致崩溃。
    【解决方案2】:

    我在 Angular 7+ 中以这种方式解决了这个问题

    <div *ngIf="formField.password.errors?.required" class="invalid-feedback">
    Password is required
    </div>
    

    【讨论】:

      【解决方案3】:

      下面的代码对我有用。这 '?'但是,在不需要 courseCategory 之后,它是 Visual Studio 代码中错误的解决方法,其中 linter 将 courseCategory.errors?.required" 标记为错误,指出“未定义必需”。因此,对于 VSCode 用户来说,在正式发布之前会有补丁。 *ngIf="courseCategory.touched &amp;&amp; courseCategory?.errors?.required"

      【讨论】:

        【解决方案4】:

        “David Anthony Acosta”已经提出了一种解决方案。我也是这样解决的:

        <div class="alert alert-danger" *ngIf="courseCategory.touched && !courseCategory.valid">
        

        (如果触摸下拉菜单,应该会显示错误消息,但没有选择任何选项)。

        【讨论】:

          【解决方案5】:

          我只是对“错误”对象进行了测试:

          <div *ngIf="formField.password.errors && formField.password.errors.required" class="invalid-feedback">
          Password is required
          </div>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-01-29
            • 2016-11-24
            相关资源
            最近更新 更多