Angular自定义表单控件(Required)不起作用。
创始人
2024-11-01 11:00:05
0

需要在自定义控件的代码中实现ControlValueAccessor接口,并在其中包括对isRequired属性的处理。

示例代码:

首先,在自定义控件中导入ControlValueAccessor:

import { Component, OnInit, Input, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

接下来,实现ControlValueAccessor接口:

@Component({ selector: 'app-custom-control', templateUrl: './custom-control.component.html', styleUrls: ['./custom-control.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CustomControlComponent), multi: true } ] }) export class CustomControlComponent implements OnInit, ControlValueAccessor {

onChange: any = () => {}; onTouched: any = () => {};

private _value: any; get value(): any { return this._value; } set value(val: any) { this._value = val; this.onChange(val); this.onTouched(); }

writeValue(val: any) { if (val !== undefined) { this._value = val; } }

registerOnChange(fn: any) { this.onChange = fn; }

registerOnTouched(fn: any) { this.onTouched = fn; }

setDisabledState(disabled: boolean) { // implement this method if needed }

}

在自定义控件的HTML模板中,需要设置isRequired属性,并绑定到内部的input元素:

最后,在父组件中使用自定义控件时,绑定isRequired属性:

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker怎么提高运气"竟然真的是有辅助app(哔哩哔哩)1、wepoker怎么提高运...
透视解密"德州透视h... 透视解密"德州透视hhpoker"其实真的有辅助挂(哔哩哔哩)德州透视hhpoker能透视中分为三种...
透视推荐"wepok... 透视推荐"wepoker永久免费脚本"真是真的是有辅助技巧(哔哩哔哩)1、wepoker永久免费脚本...
透视详情"wepok... 透视详情"wepoker怎么挂飞机"本来真的是有辅助工具(哔哩哔哩)1、首先打开wepoker怎么挂...
透视推荐"wepok... 透视推荐"wepoker黑侠辅助器"原来真的是有辅助挂(哔哩哔哩)1、玩家可以在wepoker黑侠辅...
透视辅助"约局吧是否... 透视辅助"约局吧是否有挂"确实存在有辅助app(哔哩哔哩)1、约局吧是否有挂破解器简单,约局吧是否有...
透视分享"德州局怎么... 透视分享"德州局怎么透视"一直真的是有辅助挂(哔哩哔哩)1.德州局怎么透视 选牌创建新账号,点击进入...
透视总结"wpk模拟... 透视总结"wpk模拟器是什么"本来是真的辅助神器(哔哩哔哩)wpk模拟器是什么能透视中分为三种模型:...
透视了解"wepok... 透视了解"wepoker轻量版辅助"真是存在有辅助脚本(哔哩哔哩)在进入wepoker轻量版辅助软件...
透视详情"wpk模拟... 透视详情"wpk模拟器多开"切实真的是有辅助方法(哔哩哔哩)1、wpk模拟器多开免费脚本咨询教程、w...