Notify child component about changes in Angular2

前端 未结 2 1308
野性不改
野性不改 2021-01-02 01:34

Suppose I have simple Angular2 component

@Component({ selector: \'parent\' })
@View({
    template: `
        

        
相关标签:
2条回答
  • 2021-01-02 01:41

    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

    0 讨论(0)
  • 2021-01-02 01:59

    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

    0 讨论(0)
提交回复
热议问题