Return to site

ANGULAR INTERVIEW QUESTION: What are the LifeCycle hooks?

· ngInterview,fullstack

Each Angular component has a lifecycle, which is composed of different steps: creation, display update, and destruction.

 

ngOnChanges: this methods is called first at component creation, even before ngOnInit, and each time Angular detects that component properties have been modified.

This method use the Angular object SimpleChange as parameter, to be able to compare values with previous ones.

 

 

ngOnInit: This method is called just after the first call to ngOnChanges. Its role is to be sure the component properties have been initialized with the Angular component template.

 

 

ngOnDestroy: Called last, this method is call before Angular destroys the component, when this lat one is removed from DOM.

This can happen when a use navigate from one component to another. (ie: /home to /login)

Generally, we use this method to avoid memory leaks, by unsubscribing to Async Tasks.(ie: this.myAsyncTaskSubscription.unsubscribe();)