在Angular2中的数据流动是单向的,我们常见的双向绑定的例子如下:
<input [(ngModel)]="value"/>
等价于
<input [ngModel]="value" (ngModelChange)="valueChange($event)"/>
那么我们如何实现自定义自己的组件,该组件也可以接受[(ngModel)]来实现双向绑定呢?首先来看组件的定义代码:
@Component({
selector: 'app-two-way',
template: `<input [(ngModel)]="value">`,
styleUrls: ['./two-way.component.css'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TwoWayComponent),
multi: true,
}],
})
export class TwoWayComponent implements ControlValueAccessor {
private innerValue: any = '';
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
get value(): any {
return