您可以通过以下方式在父子组件之间设置双向数据绑定:
<app-child [(counter)]="counter"></app-child>
<app-child [counter]="counter" (counterChange)="counter=$event"></app-child>
<app-child [counter]="counter" (counterChange)="onCounterChange($event)"></app-child>
根据Angular - Template Syntax - Two-way binding:
Angular 为此提供了一种特殊的双向数据绑定语法,
[(X)]。 [(x)] 语法结合了属性绑定的括号,
[x],带括号的事件绑定,(x)。
<app-child [(counter)]="counter"></app-child>
当元素具有
名为 x 的可设置属性和名为 xChange 的相应事件。
@Input() counter: number;
@Output() counterChange = new EventEmitter<number>();
双向绑定语法实际上只是一个语法糖
属性绑定和事件绑定。 Angular 脱糖
ChildComponent 绑定到这个:
<app-child [counter]="counter" (counterChange)="counter=$event"></app-child>
示例: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: `
<div style="background-color: red; padding: 10px;">
<div>{{counter}}</div>
<button (click)="increment()">increment from parent</button>
<app-child [(counter)]="counter"></app-child>
<app-child [counter]="counter" (counterChange)="counter=$event"></app-child>
<app-child [counter]="counter" (counterChange)="onCounterChange($event)"></app-child>
</div>
`
})
export class AppComponent {
counter = 0;
increment() {
this.counter++;
}
onCounterChange(counter: number) {
this.counter = counter;
}
}
@Component({
selector: 'app-child',
template: `
<div style="background-color: green; padding: 10px; margin: 10px;">
<div>{{counter}}</div>
<button (click)="increment()">increment from child</button>
</div>
`,
})
export class ChildComponent {
@Input() counter: number;
@Output() counterChange = new EventEmitter<number>();
constructor() { }
increment() {
this.counterChange.emit(++this.counter);
}
}