Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnChanges not firing when attribute changed by Observable/subscrption

I'm trying to do something after an Observable/subscribe completes. I'm changing an Input property in the subscribe( onNext ) method, but ngOnChanges never fires.

What should I be doing differently?

import { Component, EventEmitter, 
  OnInit, AfterViewInit, OnChanges, SimpleChanges,
  Input, Output
} from '@angular/core';

@Component({
  templateUrl: 'myTemplate.html'
    , providers: [ NamesService ]
})

export class MyPage  {
  @Input() names: any[];

  constructor( public namesSvc: NamesService) {}

  ngOnInit() {
    this.getNames$()
  }


  getNames$() : void {
    this.nameService.get().subscribe( 
      (result)=>{
       this.names = result;
       console.log(`getNames$, names=${this.names}`);

       // I could doSomething() here, but it doesn't seem like the correct place
       // doSomething()  

      }
      , error =>  this.errorMessage = <any>error
    )
  }

  ngOnChanges(changes: SimpleChanges) : void {
    // changes.prop contains the old and the new value...
    console.warn(`>>> ngOnChanges triggered`)
    if (changes["names"]) {
      console.warn(`>>> ngOnChanges, names=${changes["names"]}`)
      this.doSomething()
    }
  }

  doSomething(){
    console.log("doing something");
  }
}
like image 863
michael Avatar asked Jan 05 '23 06:01

michael


1 Answers

That's "as designed"

ngOnChanges() is only called when change detection updates a binding to an @Input(). If the input is changed imperatively from somewhere then it isn't called.

Just make names a getter/setter for code to be executed every time when the property is updated.

like image 130
Günter Zöchbauer Avatar answered Jan 13 '23 21:01

Günter Zöchbauer