4

I have a child component

parent.component.html

 <child-component (changeVal) = "parentObj"></child-component>

parent.component.ts

parentObj = {
  someDate = new Date()
}
// function changing the parentObj
callOnClick() {
   this.parentObj.someDate = new Date('20 June 2018'); 
}

child component.ts

@Input('changeVal')
ngOnChanges() {
 // console i never see
 console.log('parentObj Changed and got me here');
}

Why is the onChanges hook not running in this case? I am changing the input value inside the callOnClick method, isn't it supposed to fire when the value of changeVal is changed ?

1
  • Thanks for the simple solution, Ravi. KUDOS! Commented Jun 4, 2020 at 11:56

3 Answers 3

6
<child-component (changeVal) = "parentObj"></child-component>

changeVal is an input in your code, but an output in your HTML. Consider using this instead :

<child-component [changeVal] = "parentObj"></child-component>

And declare a variable as an input, not your function.

@Input() changeVal: any;
Sign up to request clarification or add additional context in comments.

2 Comments

Still can't see the console message.
Declare a variable after your decorator, functions aren't input, especially lifecycle functions
3

If I'm not mistaken, you're trying to pass an object from parent to child.

parentObj is a property. Use property binding using square brackets as follows:

<child-component [changeVal] = "parentObj"></child-component>

Also, in child.component.ts, you have to provide @Input() decorator to a property not a method.

    @Input('changeVal') changeVal = {};
    ngOnChanges() {
      // console i never see
      console.log('parentObj Changed and got me here');
    }

Comments

0

you could use the speard operator " ... " to force change detection

syntax is as follows

this.object = {...this.object};

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.