Angular自定义组件实现[(ngModel)]
预览
摘要
组件实现ControlValueAccessor接口即可
TS1interface ControlValueAccessor { 2 writeValue(obj: any): void 3 registerOnChange(fn: any): void 4 registerOnTouched(fn: any): void 5 setDisabledState(isDisabled: boolean)?: void 6}
示例代码
ts代码:
TS1import {Component, forwardRef, Input} from '@angular/core'; 2import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; 3 4@Component({ 5 selector: 'app-test-component', 6 templateUrl: './app-test-component.html', 7 providers: [ 8 { 9 provide: NG_VALUE_ACCESSOR, 10 useExisting: forwardRef(() => TestComponent), 11 multi: true 12 } 13 ] 14}) 15export class TestComponent implements ControlValueAccessor { 16 17 value: any; 18 valueChange: (value: any) => void; 19 onTouched: () => void; 20 @Input() disabled = false; 21 22 /** 23 * 表单模型的值发生变化时,将值写到自定义控件中 24 */ 25 writeValue(value: any): void { 26 this.value = value; 27 } 28 29 /** 30 * 当控件的值发生变化时,通过此函数通知表单模型进行更新 31 */ 32 registerOnChange(fn: (value: any) => void): void { 33 this.valueChange = fn; 34 } 35 36 /** 37 * 通过此函数通知表单模型标记控件的触摸状态touched为true 38 */ 39 registerOnTouched(fn: any): void { 40 this.onTouched = fn; 41 } 42 43 /** 44 * 表单模型通知控件的启用或禁用状态 45 */ 46 setDisabledState(isDisabled: boolean): void { 47 this.disabled = isDisabled; 48 } 49} 50
html代码:
HTML1<input 2 [(ngModel)]="value" 3 (ngModelChange)="valueChange($event)" 4 [disabled]="disabled" />
END
版权声明:本文为博主原创文章,遵循 CC BY-SA 4.0 版权协议,转载请附上原文出处链接和本声明。
本文链接:
分享
打赏
🥰谢谢!!