I have an angular component which has an input Person
export class Person {
public name = 'Initial Name';
}
export class PersonComponent implements OnInit, OnChanges {
@Input() public person: Person;
ngOnChanges(changes: SimpleChanges): void {
console.log('changed');
}
}
In the parent component of this component, if I replace the Person
object which is given as the input to the child component, ngOnChanges()
gets fired in the child component.
But, if I only change the name
of the Person
object from the parent component, ngOnChanges()
doesn't get fired in the child component (anyway, if I bind the person name to an html element in the child template, it gets updated).
Is there any way to get notified in the child component when a property of an input is changed?
No, the ngOnChanges hook will only fire when the reference changes. You can easily achieve what you're going for by doing this when changing the name property in the parent component:
this.person = {...this.person, name: 'new value'};
You could always create an Observable on the Person
that emits whenever a property changes.
import { Subject } from 'rxjs';
export class Person {
private _changes = new Subject<any>();
private _name = 'Initial Name';
// subscribe to this one
public changes = this._changes.asObservable();
set name(newName: string) {
this._name = newName;
this._changes.next({'name': newName});
}
get name() {
return this._name;
}
}
This way, you can subscribe to person.changes
, which will emit a value every time name
is changed
When you write person.name = 'Fred'
, the setter will be invoked, which in turn will emit the new value from the Observable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With