角度MAT:表单验证导致“ jit_nodeValue_6(...)。hasError()不是函数”

时间:2018-10-08 14:59:46

标签: angular angular-material2 angular-validation

我不确定为什么会出现以下错误:ERROR TypeError: jit_nodeValue_6(...).hasError is not a function

看来Angular不喜欢我给title.hasError()的电话。有人知道为什么吗?谢谢!

这是我的HTML模板:

<form [formGroup]="detailsForm">
    <mat-form-field >        
        <input matInput placeholder="Title" formControlName="title" name="title" #title>
        <mat-error *ngIf="title.hasError('required')">
                Title is <strong>required</strong>
        </mat-error>         
    </mat-form-field>
    ...
</form>

3 个答案:

答案 0 :(得分:1)

如果您要检查FormControl是否存在错误,则可以考虑将FormControlDirective用作FormControl的{​​{1}} 示例

@Input:

<input name="name" [formControl]="name"> 作为FormControl的属性与一起访问。? safe-navigation-operator又名猫王运算符

formGroup

修改后的代码

 detailsForm?.controls?.title?.hasError('required') 

stackblitz

答案 1 :(得分:0)

您可以按以下方式使用ngIf

*ngIf="detailsForm.get('title').hasError('required')"

因此,您必须在ngIf标签中更改mat-error,如下所示:

<form [formGroup]="detailsForm">
    <mat-form-field >        
        <input matInput placeholder="Title" formControlName="title" name="title" #title>
        <mat-error *ngIf="detailsForm.get('title').hasError('required')">
                Title is <strong>required</strong>
        </mat-error>         
    </mat-form-field>
    ...
</form>

答案 2 :(得分:0)

您可以通过使用ngModel以更简单的方式使用('hasError')

<div class="example-container">
    <form [formGroup]="detailsForm">
        <mat-form-field >        
            <input matInput placeholder="title" formControlName="title" ngModel name="title" #title="ngModel">
            <mat-error *ngIf="title?.hasError('required')">
                  <p>Required</p>
            </mat-error>         
        </mat-form-field>
    </form>
    </div>