Chris Hamilton
Chris Hamilton

Reputation: 10946

Angular - How do I implement two way binding, binding parent property to child property and vise versa?

If I have a parent component with a child component nested inside of it, how do I bind one of the parent's properties to one of the child's properties, so that changes to the child property are reflected in the parent and vise versa?

Example

Parent Component

export class AppComponent {
  values = ['apple', 'banana', 'orange', 'pear', 'melon'];
  index = 0;
  parentProp = '';
  changeProp() {
    this.parentProp = this.values[this.index++ % this.values.length];
  }
}
<p>Parent Property: {{ parentProp }}</p>
<button (click)="changeProp()">Change Parent Property</button>
<app-child></app-child>

Child Component

export class ChildComponent {
  values = ['carrot', 'cucumber', 'pepper', 'potato', 'broccoli'];
  index = 0;
  childProp = '';
  changeProp() {
    this.childProp = this.values[this.index++ % this.values.length];
  }
}
<p>Child Property: {{ childProp }}</p>
<button (click)="changeProp()">Change Child Property</button>

As you can see, you can change the value of parentProp and childProp in their respective components. How do I make it so that both parentProp and childProp are always synchronized with the same value?

Upvotes: 0

Views: 1680

Answers (1)

Chris Hamilton
Chris Hamilton

Reputation: 10946

This is called Two Way Binding: https://angular.io/guide/two-way-binding

In the child component you decorate the property with @Input() to make it an input property. You also need an EventEmitter decorated with @Output() to emit the property back to the parent. You then emit the new value of the property whenever it is changed.

The name of the EventEmitter must be the name of the input property suffixed with "Change"

Child Component TS

  @Input() childProp = '';
  @Output() childPropChange = new EventEmitter<string>();

  changeProp() {
    this.childProp = this.values[this.index++ % this.values.length];
    this.childPropChange.emit(this.childProp);
  }

Now we can easily bind this variable to the parent using banana-in-a-box notation [(🍌)]

Parent Component HTML

<app-child [(childProp)]='parentProp'></app-child>

Changes to the property in either component will be reflected in both components.

Stackblitz: https://stackblitz.com/edit/angular-ivy-en4ogt?file=src/app/app.component.html

Upvotes: 2

Related Questions