Cannot read property 'required' of null

前端 未结 5 2014
悲哀的现实
悲哀的现实 2021-02-05 06:05

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

相关标签:
5条回答
  • 2021-02-05 06:20

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

    0 讨论(0)
  • 2021-02-05 06:23

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

    0 讨论(0)
  • 2021-02-05 06:28

    I solved it this way in Angular 7+

    <div *ngIf="formField.password.errors?.required" class="invalid-feedback">
    Password is required
    </div>
    
    0 讨论(0)
  • 2021-02-05 06:37

    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"

    0 讨论(0)
  • 2021-02-05 06:39

    I simply did the test over "errors" object:

    <div *ngIf="formField.password.errors && formField.password.errors.required" class="invalid-feedback">
    Password is required
    </div>
    
    0 讨论(0)
提交回复
热议问题