Angular2 Call Function When the Input Changes

Child component:

export class Child {
    @Input() public value: string;
    public childFunction(){...}
}

Parent component:

export class Parent {
    public value2: string;
    function1(){ value2 = "a" }
    function2(){ value2 = "b" }
}

Parent view:

<child [value]="value2">

Is there any way to call childFunction() every time the value2 is changed in this structure?

Upvotes: 46

Views: 64993

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657416

You can use the ngOnChanges() lifecycle hook

export class Child {
    @Input() public value: string;

    ngOnChanges(changes) {
      this.childFunction()
    }
    public childFunction(){...}
}

or use a setter

export class Child {
    @Input() 
    public set value(val: string) {
      this._value = val;
      this.childFunction();
    }
    public childFunction(){...}
}

Upvotes: 75

Related Questions