I just found out that there are several ways to implement two way binding in a custom component. What I can't understand is the difference between them. When shoud I prefer using a component which uses banana in a box syntax (with an @input() and @Output() for the model), to implements two way binding like this component
@Component({
selector: 'app-first-component',
template: `
<p>input model value: {{ inputModel }}</p>
<button (click)="clickHandler()">Clear</button>
`
})
export class FirstComponentComponent {
@Input() inputModel: string;
@Output() inputModelChange = new EventEmitter<string> ();
clickHandler(): void {
this.inputModel = '';
this.inputModelChange.emit(this.inputModel);
}
}
and one which implements ControlValuAccessor like this
@Component({
selector: 'app-second-component',
template: `
<p>input model value: {{ inputModel }}</p>
<button (click)="clickHandler()">Clear</button>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SecondComponentComponent),
multi: true
}]
})
export class SecondComponentComponent implements ControlValueAccessor {
private inputModel: string;
private onChanged: (value: string) => void = () => {};
clickHandler(): void {
this.inputModel = '';
this.onChanged(this.inputModel);
}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
writeValue(value: string) {
this.inputModel = value;
this.onChanged(this.inputModel);
}
registerOnTouched(): void {/* ignored */}
}
I they're used in a parent component like this
<app-first-component [(inputModel)]="value"> </app-first-component>
<app-second-component [(ngModel)]="value"> </app-second-component>
As you can see they are used in the same way and also do the same job. If so, why is there ControlValueAccessor? Is there anything I can do with the second component which is not feasible with the first one?