Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify child component about changes in Angular2

Tags:

angular

events

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 ?

like image 687
Eugene Gluhotorenko Avatar asked Jul 23 '15 18:07

Eugene Gluhotorenko


Video Answer


1 Answers

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

like image 145
Denis Gursky Avatar answered Nov 02 '22 09:11

Denis Gursky