Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a property of an input of a component changed in angular

Tags:

angular

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?

like image 617
Lahiru Chandima Avatar asked Jul 15 '18 16:07

Lahiru Chandima


2 Answers

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'};
like image 195
Christian Avatar answered Oct 19 '22 20:10

Christian


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.

like image 23
user184994 Avatar answered Oct 19 '22 20:10

user184994