我不确定为什么会出现以下错误: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>
答案 0 :(得分:1)
如果您要检查FormControl
是否存在错误,则可以考虑将FormControlDirective
用作FormControl
的{{1}}
示例
@Input:
将 <input name="name" [formControl]="name">
作为FormControl
的属性与一起访问。? safe-navigation-operator
又名猫王运算符
formGroup
修改后的代码
detailsForm?.controls?.title?.hasError('required')
答案 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>