Angular 2 Component Lifecycle


Angular 2 Component Lifecycle

For each Angular 2 Component there will be some pre-defined life cycle methods like constructorngOnInit to manage the life-cycle component. Angular Framework itself is responsible to manage the life-cycle of Component we do not need to do anything.

Here is the life-cycle of Angular Component.

  1. constructor– The constructor of the component is called before any other component life-cycle method.
  2. ngOnChanges – Will be called when an input binding value changes.
  3. ngOnInit – Will be called just after constructor and after ngOnChange
  4. ngDoCheck – ngDoCheck will be triggered every time when any changes detected in component or directive.
  5. ngAfterViewInit – After component’s views are initialized
  6. ngOnDestroy – It is used to clean the component .

constructor –

constructor is one of the import life-cycle method of angular component class and It will be called before any other life-cycle method calling.

The main use of constructor is to inject the dependencies.

import {Component} from 'angular2/core';
import {StudentService} from './student.service';
@Component({
  selector: ‘student-info’,
  template: `
    <ul>
      <li *ngFor="#student of students">{{student.name}}</li>
    </ul>
  `
})
class StudentComponent {
  students: Array<any>;
  constructor(private studentService: StudentService) {
    this.students = studentService.getStudents();
  }
}

ngOnInit – 

The ngOnInit method of a component is called directly after the constructor and after the ngOnChange triggered.

ngOnInit  life-cycle method generally used is to place initialization logic like to call any method or to display any information in html page..

import {Component} from 'angular2/core';
import {StudentService} from './student.service';
@Component({
  selector: ‘student-info’,
  template: `<h1>Student Info</h1>`
})
class StudentComponent {
  constructor() {  }
  
  ngOnInit(){
     console.log("-----");
  }
}






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229