Cannot read property 'required' of null

2020-06-01 01:01发布

In the template I have a form, which one part of it has to do with rendering the list of courses:

<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>

In the browser when I select a category and press TAB (to move away from the drop-down list), I get this error on Console:

CourseComponent.html:16 ERROR TypeError: Cannot read property 'required' of null at Object.eval [as updateDirectives] (CourseComponent.html:20)

Can you help me finding out what causes this error?

Bootstrap 3.3.7 is already installed in the VS Code.

标签: angular forms
5条回答
女痞
2楼-- · 2020-06-01 01:25

One solution is already suggested by 'David Anthony Acosta'. I also solved it this way:

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

(The error message is supposed to be shown if the drop-down is touched, but no option has been selected).

查看更多
Evening l夕情丶
3楼-- · 2020-06-01 01:29

The code below worked for me. The '?' after courseCategory is not necessary, however, it's a workaround for a bug in Visual Studio code where the linter flags courseCategory.errors?.required" as an error stating that 'required is not defined. So for VSCode users, there's the patch until an official one is made. *ngIf="courseCategory.touched && courseCategory?.errors?.required"

查看更多
Bombasti
4楼-- · 2020-06-01 01:31

I simply did the test over "errors" object:

<div *ngIf="formField.password.errors && formField.password.errors.required" class="invalid-feedback">
Password is required
</div>
查看更多
劫难
5楼-- · 2020-06-01 01:34

I solved it this way in Angular 7+

<div *ngIf="formField.password.errors?.required" class="invalid-feedback">
Password is required
</div>
查看更多
做个烂人
6楼-- · 2020-06-01 01:38

Errors won't always exist, so you have to define it like this:

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

With the safe operator "?"

查看更多
登录 后发表回答