Wednesday, May 31, 2017

how to use ngOnChanges

Do you ever wish you could just splash a nested component with change and get it to react? Obviously you can easily revamp the value for an input from the outside, but this will only trigger change specific to that data point in lieu of running a desired method to update other things (a bunch of gunk, make an Observable REST query, etc.) inside of the component. Your component will thus react minimally, as if just stunned.

The fix is to use the ngOnChanges lifecycle hook (at an Angular 2 component) like so:

ngOnChanges(changes: SimpleChanges) {

 
 

Clearly, from here you may loop other methods and just do whatever outside of the straightjacket of a mere data redo. Yay! Make this happen with an import up top that ends like so:

OnChanges, SimpleChanges, SimpleChange} from '@angular/core';

 
 

It gets triggered when an @Input gets updated. Easy! I'm not really sure what SimpleChanges and SimpleChange do. This has some more on that. Also, use the implements constraint at the class declaration.

export class MyComponent implements OnInit, OnChanges {

 
 

You don't have to do this (that which is immediately above) to get the code to work, but it is a good convention.

No comments:

Post a Comment