Version: \"angular2\": \"2.0.0-beta.6\"
I would like to implement a two way binding inside a parent/child component case.
On my child component, I\'m using t
You can setup two-way data binding between parent and child component in the following ways:
According to Angular - Template Syntax - Two-way binding:
Angular offers a special two-way data binding syntax for this purpose, [(x)]. The [(x)] syntax combines the brackets of property binding, [x], with the parentheses of event binding, (x).
The [(x)] syntax is easy to demonstrate when the element has a settable property called x and a corresponding event named xChange.
@Input() counter: number;
@Output() counterChange = new EventEmitter();
The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the ChildComponent binding into this:
Example: https://stackblitz.com/edit/angular-two-way-data-binding-between-parent-and-child-component?file=src%2Fapp%2Fapp.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
template: `
{{counter}}
`
})
export class AppComponent {
counter = 0;
increment() {
this.counter++;
}
onCounterChange(counter: number) {
this.counter = counter;
}
}
@Component({
selector: 'app-child',
template: `
{{counter}}
`,
})
export class ChildComponent {
@Input() counter: number;
@Output() counterChange = new EventEmitter();
constructor() { }
increment() {
this.counterChange.emit(++this.counter);
}
}