我编写了一个实现ControlValueAccessor
接口的自定义表单控件。
@Component({
selector: 'counter',
template: `
<button (click)="increase($event)">+</button>
{{counter}}
<button (click)="decrease($event)">-</button>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CounterComponent),
multi: true
}]
})
export class CounterComponent implements OnInit, ControlValueAccessor {
private counter: number = 0;
private onChange: (_: any) => void;
private onTouched: () => void;
ngOnInit() { }
writeValue(value) {
console.log('Write value', value);
this.counter = value;
}
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
increase() {
this.counter++;
this.onChange(this.counter);
}
decrease() {
this.counter--;
this.onChange(this.counter);
}
}
但是当我使用ngModel
时,我发现writeValue会触发两次。
@Component({
selector: 'my-app',
template: '<counter [(ngModel)]="count"></counter>',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
count = 5;
}
Write value null
Write value 5
在线示例链接:https://stackblitz.com/edit/angular-ngmodel-write-value