如何正确处理自定义消息的错误?

发布于 2025-01-15 15:03:35 字数 637 浏览 5 评论 0原文

我编写了一个检查错误的函数,然后使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幻梦 2025-01-22 15:03:35

使用 get 方法来检索控件,以便您可以传递点分隔值来访问嵌套形式控制。

组件.ts

handleError = (controlName: string, errorName: string) => {
    return this.form.get(controlName).hasError(errorName);
}

组件.html

<mat-error *ngIf="handleError('myObj.field2', 'required')">Campo obbligatorio</mat-error>

Use get method to retrive control, so that you can pass dot delimated value to access nested formcontrol.

component.ts

handleError = (controlName: string, errorName: string) => {
    return this.form.get(controlName).hasError(errorName);
}

component.html

<mat-error *ngIf="handleError('myObj.field2', 'required')">Campo obbligatorio</mat-error>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文