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");
}
}
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.
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