首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角-如何实现双向绑定,绑定父属性到子属性,反之亦然?

问角-如何实现双向绑定,绑定父属性到子属性,反之亦然?
EN

Stack Overflow用户
提问于 2022-07-30 19:26:14
回答 1查看 147关注 0票数 0

如果我有一个父组件,其子组件嵌套在其子组件中,那么如何将父组件的一个属性绑定到子属性之一,以便在父属性中反映对子属性的更改,反之亦然?

示例

父组件

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

子组件

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

如您所见,您可以在各自的组件中更改parentProp和childProp的值。如何使parentProp和childProp始终与相同的值同步?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-30 19:26:14

这称为双向绑定:https://angular.io/guide/two-way-binding

在子组件中,使用@Input()装饰属性,使其成为输入属性。您还需要一个用EventEmitter修饰的@Output()来将属性发送回父属性。然后,每当该属性被更改时,就会发出它的新值。

EventEmitter 的名称必须是以"Change"后缀的输入属性的名称。

子组件TS

代码语言:javascript
复制
  @Input() childProp = '';
  @Output() childPropChange = new EventEmitter<string>();

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

现在,我们可以很容易地使用香蕉盒子表示法[()]将这个变量绑定到父变量。

父组件

代码语言:javascript
复制
<app-child [(childProp)]='parentProp'></app-child>

两个组件中对属性的更改都将反映在这两个组件中。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73178502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档