如果我有一个父组件,其子组件嵌套在其子组件中,那么如何将父组件的一个属性绑定到子属性之一,以便在父属性中反映对子属性的更改,反之亦然?
示例
父组件
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>子组件
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>如您所见,您可以在各自的组件中更改parentProp和childProp的值。如何使parentProp和childProp始终与相同的值同步?
发布于 2022-07-30 19:26:14
这称为双向绑定:https://angular.io/guide/two-way-binding
在子组件中,使用@Input()装饰属性,使其成为输入属性。您还需要一个用EventEmitter修饰的@Output()来将属性发送回父属性。然后,每当该属性被更改时,就会发出它的新值。
EventEmitter 的名称必须是以"Change"后缀的输入属性的名称。
子组件TS
@Input() childProp = '';
@Output() childPropChange = new EventEmitter<string>();
changeProp() {
this.childProp = this.values[this.index++ % this.values.length];
this.childPropChange.emit(this.childProp);
}现在,我们可以很容易地使用香蕉盒子表示法[()]将这个变量绑定到父变量。
父组件
<app-child [(childProp)]='parentProp'></app-child>两个组件中对属性的更改都将反映在这两个组件中。
Stackblitz:https://stackblitz.com/edit/angular-ivy-en4ogt?file=src/app/app.component.html
https://stackoverflow.com/questions/73178502
复制相似问题