【发布时间】:2019-06-27 21:35:20
【问题描述】:
我创建了一个反应形式并使用角度材料形式控制。
在提交表单时,我正在调用 API,该 API 正在返回错误,因为其中一个 formControl 值无效
例如Website already registered。
现在,我想在 中显示此错误消息,但错误未显示。
<mat-form-field class="full-width website"
[appearance]="matAppearance">
<mat-label>Website URL</mat-label>
<input matInput
placeholder="Website URL"
name="website"
formControlName="website">
<mat-error *ngIf="configurationForm.get('website').hasError('required')">
<strong>(required)</strong>
</mat-error>
<mat-error *ngIf="configurationForm.get('website').hasError('pattern')">
Invalid URL
</mat-error>
<mat-error *ngIf="websiteErrMsg">{{websiteErrMsg}}</mat-error>
</mat-form-field>
public submitForm() {
this.testService.register().subscribe(
sucRes => {
console.log('done);
},
errRes => {
if (errRes.error === 'Website is already registered') {
this.websiteErrMsg = 'Website Already Registered!';
}
}
);
}
问题 1:我做错了什么?
编辑:
我试过更改mat-error 或div,然后就可以了。现在想知道为什么它不适用于mat-error
【问题讨论】:
-
MatFormField仅在 FormControl 出现错误时显示mat-error元素。它不会仅仅因为您通过ngIfElse告诉它而显示。如果您在mat-form-field之外提供mat-error,那么它可以工作.. -
提交表单后有没有办法设置formcontrol错误。我已经尝试调用
this.configurationForm.get('website').setErrors({apiErr: true});并在html 中进行了必要的更改<mat-error *ngIf="configurationForm.get('website').hasError('apiErr') >some api error happened</mat-error> -
我认为您只需要使用自定义验证器来处理此问题..
-
你能提供 stackblitz 你的代码吗??
标签: angular