0
votes

I have two components (parent and a child), Im sending a custom object with name project to the child component and it updates/display just right, but when this change occurs I want to execute another function in the child component. Is it possible to detect when the project object gets updated so then I run the function in the child component?

So far I have achieved something with the following code, but Im not sure if this is the right approach.

ngDoCheck() {
    if (this.oldVal !== this.project.startTime) { 
        this.theFunctionThatIWantToRun();
        this.oldVal = this.project.startTime;;
    }
}

EDIT: I forgot to mention that the input is a complex object with arrays and different property types. In the code example Im only comparing one property of the object.

1
Check out ngOnChangekmansoor
What kman said, specifically SimpleChanges will give you exactly what you need. Search for that API on the Angular site and there's an exampleZ. Bagley

1 Answers

0
votes

In your child component:

Implement the OnChanges interface, and add the function ngOnChanges to your component like this. There you can exactly check which Input parameter has changed:

@Input() prop: number;

ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value
}

Reference: https://angular.io/api/core/OnChanges