Angular自定义组件实现[(ngModel)]
# 示例代码
ts代码:
```ts
import {Component, forwardRef, Input} from '@angular/core';
import {ControlValueAccessor, NGACCESSOR} from "@angular/forms";
@Component({
selector: 'app-test-component',
templateUrl: './app-test-component.html',
providers: [
{
provide: NGACCESSOR,
useExisting: forwardRef(() => TestComponent),
multi: true
}
]
})
export class TestComponent implements ControlValueAccessor {
value: any;
valueChange: (value: any) => void;
onTouched: () => void;
@Input() disabled = false;
/ 表单模型的值发生变化时,将值写到自定义控件中
/
registerOnChange(fn: (value: any) => void): void {
this.valueChange = fn;
}
/ 通过此函数通知表单模型标记控件的触摸状态touched为true
/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}
```
html代码:
```html
<input
[(ngModel)]="value"
(ngModelChange)="valueChange($event)"
[disabled]="disabled" />
```