46

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?

1 Answer 1

75

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(){...}
}
Sign up to request clarification or add additional context in comments.

10 Comments

In the first method, can we determine which variable is changed?
The changes parameter contains an entry for each changed input. See the "lifecycle hook" link above for more details.
I noticed ngOnChanges() only gets called in the child component whenever the parent input property gets re-assigned. If any other operation happens, like if the parent input property is an array and new values are pushed to them, the child doesn't get updated. Correct?
@Aiguo That's correct. ngOnChanges() is only called after Angulars change detection detects a change and updates an @Input() binding.
@Aiguo if its not wotk in array try to clone the array and push to the new cloned array the new property - if you want angular detect the change .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.