简体   繁体   English

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

[英]Notify child component about changes in Angular2

Suppose I have simple Angular2 component 假设我有简单的Angular2组件

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

as you can see it uses another simple component 你可以看到它使用另一个简单的组件

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

I am passing model from the parent component to the child through the angular's [property] syntax for data-binding. 我通过angular的[property]语法将modelparent组件传递给child组件以进行数据绑定。 So if I want to track some changes of model in the parent I can easily add event to the child and through the (event) syntax track the changes in the 'parent'. 因此,如果我想跟踪parentmodel某些更改,我可以轻松地向child添加事件,并通过(event)语法跟踪“父级”中的更改。 So how can I implement the opposite situation when parent changes model and child want to be notified ? 那么当parent改变modelchild想要被通知时,我怎样才能实现相反的情况呢?

You can use getters and setters to manage it. 您可以使用gettersetter来管理它。 For your example Child component must be looked like this: 对于您的示例, 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;
  }
}

Here is the plunker for your case 这是你的案件的plunker

You can put your additional logic or calculations into onChange method, that is called after all of component's bound properties are updated. 您可以将其他逻辑或计算放入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 Plunker

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

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