Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Forms 角度材料表单验证错误消息赢得';别走开_Forms_Angular_Angular Material2 - Fatal编程技术网

Forms 角度材料表单验证错误消息赢得';别走开

Forms 角度材料表单验证错误消息赢得';别走开,forms,angular,angular-material2,Forms,Angular,Angular Material2,我有一个物料表单,其中我有一个MdInput: <md-form-field class="input-full-width"> <input mdInput class="form-control" type="text" placeholder="Description" formControlName="periodDesc"> <md-error *ngIf="fb.get('periodDesc').errors.required">

我有一个物料表单,其中我有一个
MdInput

<md-form-field class="input-full-width">
    <input mdInput class="form-control" type="text" placeholder="Description" formControlName="periodDesc">
    <md-error *ngIf="fb.get('periodDesc').errors.required">This field is required</md-error>
</md-form-field>

此字段必填
触摸字段但未键入文本时,将显示验证消息。但是,即使我尝试在此处键入文本,验证消息仍然存在:

编辑1:

当我改为这样做时,问题得到了解决:

<md-error *ngIf="fb.hasError('required', ['periodDesc'])">This field is required</md-error>
此字段为必填字段

然而,我的问题是,为什么这个问题首先会发生?上一个案例有什么问题吗?因为我在其他地方使用它,而第二个案例不起作用。Ref:

原因是当formControl没有验证程序错误时(请参见),fb.get('periodDesc')。错误将返回null。因此,您当前的方式将抛出
null错误
,就像
找不到null所需的


使用
fb.get('periodDesc').hasrerror('required')
而不是
fb.get('periodDesc').errors.required
来防止上述错误。

我在回答中已经说明了原因。见第一段。