Angular 4

Angular 4 Tutorial : Component Lifecycle

Component lifecycle

Hello everyone, in the last post, http://www.mytechthinking.in/2017/10/12/angular-4-tutorial-view-encapsulation-and-local-references/ , we learned about the view encapsulation and various ways to pass contents to DOM. In this post, we will learn about the lifecycle of the components. Let’s discuss them one by one.

Component lifecycle hooksngOnInit : This is called on the initialization of the component.

ngOnChanges : This is called when an input property changes

ngDoCheck : This is called when anything changes. Changes can be text entered, coloured changed, the position changed anything.

ngAfterContentInit : This is called after the content (ng-content) of the component is rendered into the view.

ngAfterContentChecked : This is called every time the projected content has been checked.

ngAfterViewInit : This is called after the initialization of component view and its child view.

ngAfterViewChecked : This is called every time the projected view has been checked.

ngOnDestroy : This is called before destroying the component.

You can try implementing the above hooks and see when they are called. One sample is given below.

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.scss']
})
export class DisplayComponent implements OnInit {
@Input() colorElement: {color: string, content: string};
  constructor() { }
  ngOnInit() {
    console.log('ngOnInit hook Called');
  }
}

That’s all for the lifecycle hooks of angular, in the next post, http://www.mytechthinking.com/2017/12/10/angular-4-5-tutorial-understanding-directives/ , we will learn about the angular directives and how to create custom directives of our own.

Leave a Reply

Your email address will not be published. Required fields are marked *