Issue
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?
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>
How do I make it so that both parent and child properties always have the same value?
Solution
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
Answered By - Chris Hamilton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.