Explain the life cycle hooks of Angular 2 application
Angular 2 component/directive has lifecycle events, managed by @angular/core. It creates the component, renders it, creates and renders its children, processes changes when its data-bound properties change, and then destroys it before removing its template from the DOM. Angular provides a set of lifecycle hooks(special events) which can be tapped into this lifecycle and perform operations when required. The constructor executes prior to all lifecycle events. Each interface has a single hook method prefixed with ng. For example,_ngOnint_interface has_Oninit_method that must be implemented in the component.
Some of the events are applicable for both component/directives while few are specific to components.
- ngOnChanges: Responds when angular sets its data-bound property which receives the current and previous object values.
- ngOnInit: Initializes the component/directive after first ngOnChange triggers. This is most frequently used method to retrieve the data for the template from a back-end service.
- ngDoCheck: Detect and act upon changes occuring outside Angular context. It is called when every change detection run.
- ngOnDestroy: Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.
Component-specific hooks:
- ngAfterContentInit: Component content has been initialized
- ngAfterContentChecked: After Angular checks the bindings of the external content that it projected into its view.
- ngAfterViewInit: After Angular creates the component’s view.
- ngAfterViewChecked: After Angular checks the bindings of the component’s view.