2

I have an object in my parent component that looks like this and is passed down to my child component (app-custom-component):

myObject = {
  name: 'John'
}
...
<app-custom-component [inputObject]="myObject"></app-custom-component>

And in my child component (app-custom-component) I do this:

@Input() inputObject;
displayName = '';

ngOnInit() {
  this.displayName = this.inputObject.name;
}
...
<label>{{displayName}}</label>

But when I change the myObject.name in the parent component it doesn't update the child component's displayName.

How can I make displayName update when I change myObject.name in the parent component?

https://stackblitz.com/edit/angular-mqiorv

1
  • It works just fine, open your console for errors. Commented Dec 7, 2018 at 9:57

5 Answers 5

5

It would be pretty easier with getter for displayName.

@Input() inputObject;

ngOnInit() {

}

get displayName(){
   return this.inputObject.name;
}

...

<label>{{displayName}}</label>
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect thank you! Would you mind explaining how this works or referencing docs please? :)
Getter will be called whenever Angular goes throgh Change Detection Process which ensure that latest changes are being reflected in the html template.
I see. Thank you!
3

Use getter and setter methods for inputs

@Input() 
get inputObject()  {
    return this.displayName;
}
set inputObject(value) {
     this.displayName = this.inputObject.name;
}

Comments

1

As far as I'm aware, onInit() only gets executed once, when the component is initialized. Try putting your code in the ngOnChanges() as well.

ngOnChanges() {
  this.displayName = this.inputObject.name;
}

1 Comment

He coould simply create a getter for display name istead
0

You can use ngOnChange() and track all changes of related @Input.

Comments

0

I would recommend to avoid getter for this, so you don't have unnecessary re-rendering.

ngOnChanges(changes: SimpleChanges) {
  this.displayName = changes.inputObject.currentValue.name;
}

Make sure to implement OnChanges interface too.

Comments

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.