The common questions ask bye most of Angular 2 lovers,
“Could anyone tell me about the usage of ngOnInit if we already have a constructor?” but Angular 2 provides life cycle hook ngOnInit by default.
Angular 2 Components and Directives has multiple life-time hooks where we custom logic can be executed.
Stayed Informed - What Are Components in Angular 5,4 and 2?
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().
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<any>; 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.
import {Component, OnInit} from '@angular/core'; export class App implements OnInit{ constructor(){ } ngOnInit(){ } }
Angular 2 ngOnDestroy :-
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); } }
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