gpt4 book ai didi

angular - 组件包装时如何将formControl标记为已触摸

转载 作者:行者123 更新时间:2023-12-03 23:51:46 25 4
gpt4 key购买 nike

我试图构建一个 Angular 组件来包装整个 Angular Material 的 mat-form-field。

  <mat-form-field>
<input matInput type="text" placeholder="{{ label }}" [(ngModel)]="_value"
[required]="required" [disabled]="_disabled"
(input)="intenrnalValueChange()" />
<mat-hint>{{ hint }}</mat-hint>
<mat-error>{{ getError() }}</mat-error>
</mat-form-field>

该组件运行良好,除了有点麻烦。我无法将其标记为已触摸,我相信这是由于组件架构。我尝试了一些 StackOverflow(和其他)的解决方案,它们以传统方式运行良好,但不适用于我的组件。

    this.form.get('field').markAsTouched(); // should work
this.form.markAsTouched(); // should not work
this.form.markAllAsTouched(); // should work

我想标记一个按钮触摸的字段,它将显示所有无效的字段(以及它们的错误消息)。

我创建了一个简化的项目,可以在其中重现问题。我希望当单击按钮时,该字段变为红色并且消息出现在下方。它不会发生,但如果单击并模糊该字段,则会显示错误。

https://stackblitz.com/edit/angular-7mghym

问题是:如何更改我的项目(保留组件)以使按钮具有与单击和模糊字段相同的效果?

最佳答案

你的方法有几个问题;

首先,您正在实现 ControlValueAccessor但是你的InputComponent有一个 @Input命名为窗体控件。因此,当您绑定(bind) form.controls.fieldapp-input您的表单未与 ControlValueAccessor 交互。

<app-input label="Test" hint="It is a test" [formControl]="form.controls.field" required></app-input>

docs 中所述;

ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM (html input element)



第二个问题出现在这里;在 InputComponent DOM(html 输入元素)和 ControlValueAccessor 之间的通信通过 ngModel 处理它基本上是一个明确创建的 FormControl 的包装器。在引擎盖下。

由于这些; form.controls.field FormControl 与实际输入元素没有通信,而 ngModel 则有。这就是为什么当您手动聚焦/模糊输入元素时,它会显示错误状态但 this.form.get('field').markAsTouched();不做任何事情。

第三个问题是;即使你制作 ControlValueAccessor通过删除 @Input formControl 来工作来自 InputComponent并在没有 ngModel 的情况下与 html 输入通信;仍然, mat-form-field将无法与底层 input 交互(即获取错误状态)元素,因为它需要实现 MatFormFieldControl

第四个问题是,当使用 ReactiveForms 时,验证(例如在您的情况下需要)和禁用状态必须通过 FormControl 处理,而不是隐式处理。

好消息是,所有这些问题都有一个非常简单的解决方案,无需实现 ControlValueAccessor只需将 formControl 传递给 InputComponent 并将其绑定(bind)到 html 输入。

这是一个工作示例; https://stackblitz.com/edit/angular-fwdrv9

希望对您有所帮助,祝您有美好的一天。

关于angular - 组件包装时如何将formControl标记为已触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56496834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com