Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular subscribe to @Input object change

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

like image 920
Freddy Bonda Avatar asked Dec 10 '25 08:12

Freddy Bonda


2 Answers

It would be pretty easier with getter for displayName.

@Input() inputObject;

ngOnInit() {

}

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

...

<label>{{displayName}}</label>
like image 53
Sunil Singh Avatar answered Dec 14 '25 04:12

Sunil Singh


Use getter and setter methods for inputs

@Input() 
get inputObject()  {
    return this.displayName;
}
set inputObject(value) {
     this.displayName = this.inputObject.name;
}
like image 32
Sachila Ranawaka Avatar answered Dec 14 '25 03:12

Sachila Ranawaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!