Angular Material 表单验证错误 [英] Angular Material forms validation errors

查看:29
本文介绍了Angular Material 表单验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个材料表单,其中有一个输入框:

I have a material form in which I have an input box:

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

表单生成器:

this.apprperiod = this.fb.group({
      'periodDesc' : new FormControl(this.periodDesc, [Validators.required,Validators.maxLength(50)])
    }, {validator: CustomValidator.validate});

加载时出现以下错误:

错误类型错误:无法读取未定义的属性hasError"
在 Object.TestComponent._co [作为 updateDirectives] (test.html:33)
在 Object.debugUpdateDirectives [作为 updateDirectives] (core.es5.js:13075)
在 checkAndUpdateView (core.es5.js:12255)
在 callViewAction (core.es5.js:12620)
在 execComponentViewsAction (core.es5.js:12552)
在 checkAndUpdateView (core.es5.js:12261)
在 callViewAction (core.es5.js:12620)
在 execEmbeddedViewsAction (core.es5.js:12578)
在 checkAndUpdateView (core.es5.js:12256)
在 callViewAction (core.es5.js:12620)

ERROR TypeError: Cannot read property 'hasError' of undefined
at Object.TestComponent._co [as updateDirectives] (test.html:33)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
at checkAndUpdateView (core.es5.js:12255)
at callViewAction (core.es5.js:12620)
at execComponentViewsAction (core.es5.js:12552)
at checkAndUpdateView (core.es5.js:12261)
at callViewAction (core.es5.js:12620)
at execEmbeddedViewsAction (core.es5.js:12578)
at checkAndUpdateView (core.es5.js:12256)
at callViewAction (core.es5.js:12620)

推荐答案

因为你必须像这样从表单中获取控件:

Because you have to get the control from the form like this :

<md-error *ngIf="apprperiod.get('periodDesc').errors.required">This field is required</md-error>

或者

<md-error *ngIf="apprperiod.hasError('required', ['periodDesc'])">This field is required</md-error>

这篇关于Angular Material 表单验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆