我有一个材料表单,其中有一个输入框:
<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>
Formbuilder:
this.apprperiod = this.fb.group({
'periodDesc' : new FormControl(this.periodDesc, [Validators.required,Validators.maxLength(50)])
}, {validator: CustomValidator.validate});
加载时出现以下错误:
错误类型错误:无法读取属性&#39; hasError&#39;未定义的 在Object.TestComponent._co [as updateDirectives](test.html:33)
at Object.debugUpdateDirectives [as 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)
at execEmbeddedViewsAction(core.es5.js:12578)
在checkAndUpdateView(core.es5.js:12256)
在callViewAction(core.es5.js:12620)
答案 0 :(得分:2)
因为您必须从以下表单中获取控件:
<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>
答案 1 :(得分:1)
您可以在component
中创建方法,以检查状态并验证FormGroup
中的字段:
checkInvalidTouched(field: string) {
return (
!this.apprperiod.get(field).valid &&
(this.apprperiod.get(field).touched || this.formulario.get(field).dirty)
);
}
checkCustomValidator() {
const formField = this.formulario.get('periodDesc');
if (formField.errors) {
return formField.errors['customValidator'] && checkValidTouched('periodDesc');
}
}
然后在*ngIf
上使用此方法作为子句:
<md-form-field class="input-full-width">
<input mdInput class="form-control emp-info-input" type="text" placeholder="Description" formControlName="periodDesc">
<md-error *ngIf="checkIfRequired('periodDesc')">This field is required.</md-error>
<md-error *ngIf="checkCustomValidator('periodDesc')">Custom validator return error.</md-error>
</md-form-field>