Thursday, December 24, 2020

13. What is the possible order of life-cycle hooks?

 Angular 2 Complete lifecycle hook interface inventory:-


1. ngOnChanges - called when an input binding value changes.
2. ngOnInit - after the first ngOnChanges.
3. ngDoCheck - after every run of change detection.
4. ngAfterContentInit - after component content initialized.
5. ngAfterContentChecked - after every check of component content.
6. ngAfterViewInit - after component's view(s) are initialized.
7. ngAfterViewChecked - after every check of a component's view(s).
8. ngOnDestroy - just before the component is destroyed.


Angular 2 Lifecycle Events Log:-
1. onChanges
2. onInit
3. doCheck
4. afterContentInit
5. afterContentChecked
6. afterViewInit
7. afterViewChecked
8. doCheck
9. afterContentChecked
10.afterViewChecked
11.onChanges
12.doCheck
13.afterContentChecked
14.afterViewChecked
15.onDestroy


Angular 2 Constructors:-
The constructor is a default method runs when component is being constructed.
The constructor is a typescript feature and it is used only for a class instantiations and nothing to do with Angular 2.





The constructor called first time before the ngOnInit().

Example as,
import {Component} from 'angular2/core';
import {UserService} from './userService';

@Component({
  selector: ‘list-user’,
  template: `< ul >< li *ngFor="#user of users">{{user.name}}</ li >< / ul >`
})

class App_Component {
  users:Array;
  constructor(private _userService: UserService) {
      this.users = _userService.getUsers();
  }
}

Angular 2 ngOnInit and ngOnChanges:-
The ngOnInit event is an Angular 2 life-cycle event method that is called after the first ngOnChanges and the ngOnInit method is use to parameters defined with @Input otherwise the constructor is OK.

The ngOnInit is called after the constructor and ngOnInit is called after the first ngOnChanges.

The ngOnChanges is called when an input or output binding value changes.


Examples as,
import {Component, OnInit} from '@angular/core';
export class App implements OnInit{
  constructor(){
  }

  ngOnInit(){
  }
}

Angular 2 ngOnDestroy :-

The ngDestroy directive is called in a component lifecycle just before the instance of the component is finally destroyed.

Example as,
@Directive({
    selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {

  //Call Constructor and set hello Msg.
  constructor() {
    this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
  }

  //Destroy to the component
  ngOnDestroy() {
     window.clearInterval(this.helloMsg);
  }
}

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...