3

I have an input variable called model for childComponent. @Input () model: any;

I have a parent control parentControl that send the updated input variable to childComponent.

How do I code childComponent to react to model changes? I want a childComponent call made when model changes.

Thoughts?

3

1 Answer 1

7

Consider using ngOnChanges() lifecycle

@Input() model: any;
ngOnChanges(model: any) {
    this.doSomething(model);
}
Sign up to request clarification or add additional context in comments.

5 Comments

and if there are multiple input parameters will I have one ngOnChanges for each input variable?
yes you need to do that, there is no such watchgroup in angular2 like we have in angularjs
@reza no, you don't, the argument to the single ngOnChanges method is actually SimpleChanges, which contains the changes to any of the inputs. You can see this in the docs linked, not sure why the author is saying otherwise.
@reza yes, you are right! actually i was mentioning about using a set_method , in that case you need separate ones. but ngOnchanges usually give whatever the inputs if they are changed. sorry i have not read your comment properly. angular.io/api/core/OnChanges
This is close, but is not actually correct. I will give an example with a boolean data binding ``` @Input() yourData: boolean; ngOnChanges(changes: SimpleChanges) { console.log('changes: ', changes); // this will console out all of the changes it detected. console.log('changes.yourData: ', changes.yourData); // this will console out yourData old and yourData new. } ``` the changes.yourData would output like this in console. ``` changes.yourData: { currentValue: true, firstChange: false, previousValue: Undefined } ``` previousValue will update on second change

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.