输入更改时的Angular2调用函数

时间:2016-09-05 12:57:32

标签: javascript angular data-binding

子组件:

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

父组件:

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

家长观点:

<child [value]="value2">

每次在这个结构中更改value2时,有没有办法调用childFunction()?

1 个答案:

答案 0 :(得分:33)

您可以使用ngOnChanges() lifecycle hook

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

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

或使用setter

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