Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular- Component LifeCycle

In Angular, a Component instance has a Lifecycle that starts with instantiating the component class and rendering the view with its child view.

The lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed.


The sequence of Lifecycle events

After the application instantiates a component or directive by calling its constructor, Angular calls the hook methods you have implemented at the appropriate point in the lifecycle of that instance.

Angular executes hook methods in the following sequence.

Respond to Lifecycle Events

Respond to events in the lifecycle of a component or directive by implementing one or more of the lifecycle hook interfaces in the Angular core library.

Each interface defines the prototype for a single hook method, whose name is the interface name prefixed with ng. For example, the OnInit interface has a hook method named ngOnInit().

Let's see in the code, how to implement the lifecycle hook interfaces?
import {
  AfterContentChecked,
  AfterContentInit,
  AfterViewChecked,
  AfterViewInit,
  Component,
  DoCheck,
  OnInit,
} from '@angular/core';
import {
  AbstractControl,
  FormControl,
  ValidationErrors,
  ValidatorFn,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent
  implements
    OnInit,
    DoCheck,
    AfterContentInit,
    AfterContentChecked,
    AfterViewInit,
    AfterViewChecked
{
  ngOnInit(): void {
    console.log('ngOInit Called!!');
  }
  ngDoCheck(): void {
    console.log('ngDoCheck Called!!');
  }
  ngAfterContentInit(): void {
    console.log('ngAfterContentInit Called!!');
  }
  ngAfterContentChecked(): void {
    console.log('ngAfterContentChecked Called!!');
  }
  ngAfterViewInit(): void {
    console.log('ngAfterViewInit Called!!');
  }
  ngAfterViewChecked(): void {
    console.log('ngAfterViewChecked Called!!');
  }
}

In the above code, we have implemented the following Lifecycle Hook Interfaces OnInitDoCheckAfterContentInitAfterContentCheckedAfterViewInitAfterViewChecked.

After running the above code, we can see the sequence of life cycle hook methods as below-



This post first appeared on Dot Net World, please read the originial post: here

Share the post

Angular- Component LifeCycle

×

Subscribe to Dot Net World

Get updates delivered right to your inbox!

Thank you for your subscription

×