Angular › Data Binding
How would you create a custom two way binding for your own component's custom property?
AdvancedAnswer
You define a regular Input property and a matching Output property whose name is the input's name followed by the word Change, emitting the new value whenever it changes. Angular then recognizes this pattern automatically, allowing consumers of your component to use the same banana in a box syntax as with built in form controls.
@Component({
selector: 'app-counter',
template: `<button (click)="increment()">{{ value }}</button>`
})
export class CounterComponent {
@Input() value = 0;
@Output() valueChange = new EventEmitter<number>();
increment() {
this.value++;
this.valueChange.emit(this.value);
}
}
// Used as: <app-counter [(value)]="myCount"></app-counter>Real-world example A custom counter component supports the same convenient two way binding syntax as a built in form input, letting a parent component keep its own count variable automatically synced with the counter's internal value.