繁体   English   中英

通知子组件有关Angular2中的更改

[英]Notify child component about changes in Angular2

假设我有简单的Angular2组件

@Component({ selector: 'parent' })
@View({
    template: `
        <p>Parent {{ data }}</p>
        <child [model]="data"></child>
    `,
    directives : [Child]
})
export class Parent {
    data: number = 42;
}

你可以看到它使用另一个简单的组件

@Component({
    selector: 'child',
    properties : ['model']
})
@View({
    template: `
        <p>Child {{ model }}</p>
    `,
})
export class Child {
    model: number;
}

我通过angular的[property]语法将modelparent组件传递给child组件以进行数据绑定。 因此,如果我想跟踪parentmodel某些更改,我可以轻松地向child添加事件,并通过(event)语法跟踪“父级”中的更改。 那么当parent改变modelchild想要被通知时,我怎样才能实现相反的情况呢?

您可以使用gettersetter来管理它。 对于您的示例, Child组件必须如下所示:

@Component({
  selector: 'child',
  properties : ['model']
})
@View({
  template: `
    <p>Child {{ model }}</p>
  `,
})
class Child {
  _model: number;

  set model(newModelValue) {
    // Here we are
    console.log('new model value: ' + newModelValue)
    this._model = newModelValue;
  }

  get model() {
    return this._model;
  }
}

这是你的案件的plunker

您可以将其他逻辑或计算放入onChange方法,该方法在更新所有组件绑定属性后调用。

@Component({
    selector: 'child',
    properties : ['model']
})
@View({
    template: `
        <p>Child {{ model }}</p>
    `,
})
class Child {
    model: number;

    onChange(map){
      if(map.model) {
        console.log('doing crazy stuff here');
        console.log(map.model); //SimpleChange {previousValue: 43, currentValue: 44}
      }
    }
}

Plunker

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM