如何正确处理自定义消息的错误?
我编写了一个检查错误的函数,然后使用 ngIf 来显示(或不显示)自定义文本。这样:
// ts
handleError = (controlName: string, errorName: string) => {
return this.form.controls[controlName].hasError(errorName);
}
// html
<mat-error *ngIf="handleError('tipo', 'required')">Campo obbligatorio</mat-error>
它非常适合“一级”表单组。但是嵌套表单组又如何呢?例如:
this.form = this.fb.group({
field1: [data.field1, [Validators.required]],
myObj: this.fb.group({
field2: [data.myObj.field2, [Validators.required]],
})
});
这里似乎崩溃了(在控制台上说无法读取未定义的属性(读取'hasError'))。
迭代任何嵌套表单组并检查错误的最佳方法是什么?
I write a function that check the errors, and than i use ngIf
to display (or not) a custom text. this way:
// ts
handleError = (controlName: string, errorName: string) => {
return this.form.controls[controlName].hasError(errorName);
}
// html
<mat-error *ngIf="handleError('tipo', 'required')">Campo obbligatorio</mat-error>
It works nice for "one-level" form group. But what about nested form group? Such as:
this.form = this.fb.group({
field1: [data.field1, [Validators.required]],
myObj: this.fb.group({
field2: [data.myObj.field2, [Validators.required]],
})
});
Here it seems to crash (saying Cannot read properties of undefined (reading 'hasError') on console).
What's so the best approch to iterate any nested formgroup and check for errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 get 方法来检索控件,以便您可以传递点分隔值来访问嵌套形式控制。
组件.ts
组件.html
Use get method to retrive control, so that you can pass dot delimated value to access nested formcontrol.
component.ts
component.html