Advertisement
Advanced Angular, Data Binding

How would you create a custom two way binding for your own component's custom property?

Short answer

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.

Save Angular mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • What happens if you forget to emit the new value inside the valueChange output?
  • How is this pattern related to how ngModel itself is implemented internally?
Related topics