angular - 使用 ControlValueAccessor 的有效信息
问题描述
我正在基于ControlValueAccessor
.
如何在此类组件中获取验证信息?
这是示例:https ://stackblitz.com/edit/angular-ngmodel-valid?file=src/app/text-input.component.ts
自定义字段是required
.
在TextInputComponent
我指的是NgModel
但它总是valid
。
{{formGroup.get('text').valid}}
给我正确的价值。
解决方案
使用 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" />
推荐阅读
- javascript - Javascript:如何获取对象或数组的`prototype`或`__proto__`的所有属性
- javascript - 点击提交时如何显示表格并将表单值传递给html和js后端?
- javascript - 如何按月和年对日期数组进行分组
- windows - Powershell 文件随未来和过去时间更新
- python - 在 matplotlib 3d 图上设置轴限制(python)
- java - 带有 JsonTypeInfo 的 Spring Boot Jackson defaultImpl
- typescript - 如何为静态类成员提供类型
- linux-kernel - 使用 Yocto 使用补丁集成内核中的更改
- php - 如何在后端 PHP API 中检查 android 应用内购买订阅是否有效或过期
- javascript - 传递给 useContext 的 useState 不更新状态