首页 > 解决方案 > 使用 ControlValueAccessor 的有效信息

问题描述

我正在基于ControlValueAccessor.

如何在此类组件中获取验证信息?

这是示例:https ://stackblitz.com/edit/angular-ngmodel-valid?file=src/app/text-input.component.ts 自定义字段是required.

TextInputComponent我指的是NgModel但它总是valid{{formGroup.get('text').valid}}给我正确的价值。

标签: angularangular-forms

解决方案


使用 ControlValueAccessor 时,您必须重新构建您应该查看的 NgModel。通过自己创建输入,您必须注意自定义输入的有效性,而不是内部输入。

我的意思是,应该看到app-text-input ,并像使用内部输入一样使用它。内部输入上的 NgModel(无关紧要),仅用于新组件的 HTML 模板。

简单地说,表单中输入的引用是对app-text-input组件的引用。并且使用 ControlValueAccessor 接口中的方法,您需要更新和控制值,就像本机输入本身一样。

例如:

<form ngForm="form">
  // the ngForm keeps the custom-inputs model

  // we put required here as this is now where we reference the model
  <custom-input [(ngModel)]="value" required>

    // this is just for templating, when you updating this value you must call the method writeValue, which sets the value of the custom-input which then validates the control.
    <input value="value" />

  </custom-input>

</form>

另一种解决方案 您也可以使用@Input 或@Attribute 传递属性。

我已经编辑了你的stackblitz

在此示例中,您只需传递验证:

app.component.html

<custom-input required=true>
</custom-input>

自定义输入.component.ts

@Input() required: boolean;

custom-input.component.html

<input [required]="required" />

推荐阅读