NG Life Cycle Hooks - suniladhya/Advantage GitHub Wiki

OnChanges

OnInit OnDestroy

The Life cycle methods are automatically invoked. Even if the corresponding interfaces are not implemented.

Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys before removing from the DOM. Lifecycle hooks are provided in @Angular/core

Angular provides lifecycle hooks for change detection(OnChanges (I)

constructor should be used only for local variable initializations

Component and directive has a full lifecycle managed by Angular. OnChanges cnB for change detection of input properties. When parentComponentChanges@Input, Child's ngOnChanges() Executes.

ngOnInit() is called only one time after the component/directive is constructed ngOnDestroy() is called just before component/directive is destroyed.

ngOnInit() is used to perform complex logic and fetching data. ngOnDestroy() is used to release resources to avoid memory leaks.

All complex logic and data fetching related task should be performed in ngOnInit() so that initializing component/directive will be easy and we need not to think about their complexity.

  1. Perform complex initialization in ngOnInit() and not in constructor.
  2. If we need to fetch data then it should be done in ngOnInit() and not in constructor so that we should not worry while initializing component. A constructor should perform only local variable initialization.

OnDestroy OnDestroy interface is a lifecycle hook. It has a method ngOnDestroy(). It is called for cleanup logic when a component, directive, pipe or service is destroyed. ngOnDestroy() is called just before component/directive is about to be destroyed by Angular. It can be used for following purposes.

  1. Stop interval timers.
  2. Unsubscribe Observables.
  3. Detach event handlers.
  4. Free resources that will not be garbage collected automatically.
  5. Unregister all callbacks.

ngDoCheck() Detect and act upon changes that Angular can't or won't detect on its own.

Called during every change detection run, immediately after ngOnChanges() and ngOnInit().

ngAfterContentInit() Respond after Angular projects external content into the component's view / the view that a directive is in.

Called once after the first ngDoCheck().