简体   繁体   中英

Notify child component about changes in Angular2

Suppose I have simple Angular2 component

@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. 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'. So how can I implement the opposite situation when parent changes model and child want to be notified ?

You can use getters and setters to manage it. For your example Child component must be looked like this:

@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

You can put your additional logic or calculations into onChange method, that is called after all of component's bound properties are updated.

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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