typescript - How to detect when an @Input() value changes in Angular2 -
i have parent component (categorycomponent), child component (videolistcomponent) , apiservice.
i have of working fine i.e. each component can access json api , relevant data via observables.
currently video list component gets videos, filter videos in particular category, achieved passing categoryid child via @input()
.
categorycomponent.html
<video-list *ngif="category" [categoryid]="category.id"></video-list>
this works , when parent categorycomponent category changes categoryid value gets passed through via @input()
need detect in videolistcomponent , re-request videos array via apiservice (with new categoryid).
in angular1 have done $watch
on variable. best way handle this?
actually, there 2 ways of detecting , acting on when input changes in child component in angular2+ :
you can use ngonchanges() lifecycle method mentioned in older answers:
@input() categoryid: string; ngonchanges(changes: simplechanges) { this.dosomething(changes.categoryid.currentvalue); // can use categoryid.previousvalue , // categoryid.firstchange comparing old , new values }
documentation links: ngonchanges, simplechanges, simplechange
demo example: @ this plunkeralternately, can use input property setter follows:
private _categoryid: string; @input() set categoryid(value: string) { this._categoryid = value; this.dosomething(this._categoryid); } categoryid(): string { return this._categoryid; }
documentation link: here.
demo example: @ this plunker.
which approach should use?
if component has several inputs, then, if use ngonchanges(), changes inputs @ once within ngonchanges(). using approach, can compare current , previous values of input has changed , take actions accordingly.
however, if want when particular single input changes (and don't care other inputs), might simpler use input property setter. however, approach not provide built in way compare previous , current values of changed input (which can ngonchanges lifecycle method).
edit 2017-07-25: angular change detection may still not fire under circumstances
normally, change detection both setter , ngonchanges fire whenever parent component changes data passes child, provided data js primitive datatype(string, number, boolean). however, in following scenarios, not fire , have take actions in order make work.
if using nested object or array (instead of js primitive data type) pass data parent child, change detection (using either setter or ngchanges) might not fire, mentioned in answer user: muetzerich. solutions here.
if mutating data outside of angular context (i.e., externally), angular not know of changes. may have use changedetectorref or ngzone in component making angular aware of external changes , thereby triggering change detection. refer this.
Comments
Post a Comment