DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • The Power of @ngrx/signalstore: A Deep Dive Into Task Management
  • How To Make a Windows Keylogger By Yourself
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Code Play #1: WebSockets With Vert.x and Angular

Trending

  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Docker Base Images Demystified: A Practical Guide
  • Building an AI/ML Data Lake With Apache Iceberg
  • Driving DevOps With Smart, Scalable Testing
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular 6, Part 3: Lifecycle of a Component

Angular 6, Part 3: Lifecycle of a Component

The lifecycle methods that Angular comes with a powerful way to work with components. Read on to learn how to implement these in your code.

By 
Debasis Saha user avatar
Debasis Saha
·
Jul. 25, 18 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
154.6K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will discuss the lifecycle of components. Since, in Angular, a component is the main building block the application, it is very important for us to understand the lifecycle processing steps of the components so that we can implement that in our applications.

Lifecycle Method

In Angular, every component has a life-cycle, a number of different stages it goes through. There are 8 different stages in the component lifecycle. Every stage is called as lifecycle hook event. So, we can use these hook events in different phases of our application to obtain control of the components. Since a component is a TypeScript class, every component must have a constructor method. The constructor of the component class executes, first, before the execution of any other lifecycle hook events. If we need to inject any dependencies into the component, then the constructor is the best place to inject those dependencies. After executing the constructor, Angular executes its lifecycle hook methods in a specific order.

Component Life Cycle Hook

These stages are mainly divided into two phases – one is linked to the component itself and another is linked to the children of that component.

  • ngOnChanges – This event executes every time when a value of an input control within the component has been changed. Actually, this event is fired first when a value of a bound property has been changed. It always receives a change data map, containing the current and previous value of the bound property wrapped in a SimpleChange.
  • ngOnInit – This event initializes after Angular first displays the data-bound properties or when the component has been initialized. This event is basically called only after the ngOnChanges()events. This event is mainly used for the initialize data in a component.
  • ngDoCheck – This event is triggered every time the input properties of a component are checked. We can use this hook method to implement the check with our own logic check. Basically, this method allows us to implement our own custom change detection logic or algorithm for any component.
  • ngAfterContentInit –  This lifecycle method is executed when Angular performs any content projection within the component views. This method executes when all the bindings of the component need to be checked for the first time. This event executes just after the ngDoCheck() method. This method is basically linked with the child component initializations.
  • ngAfterContentChecked – This lifecycle hook method executes every time the content of the component has been checked by the change detection mechanism of Angular. This method is called after the ngAfterContentInit() method. This method is also called on every subsequent execution of ngDoCheck(). This method is also mainly linked with the child component initializations.
  • ngAfterViewInit – This lifecycle hook method executes when the component’s view has been fully initialized. This method is initialized after Angular initializes the component’s view and child views. It is called after ngAfterContentChecked(). This lifecycle hook method only applies to components.
  • ngAfterViewChecked – This method is called after the ngAterViewInit() method. It is executed every time the view of the given component has been checked by the change detection algorithm of Angular. This method executes after every subsequent execution of the ngAfterContentChecked(). This method also executes when any binding of the children directives has been changed. So this method is very useful when the component waits for some value which is coming from its child components.
  • ngOnDestroy – This method will be executed just before Angular destroys the components. This method is very useful for unsubscribing from the observables and detaching the event handlers to avoid memory leaks. Actually, it is called just before the instance of the component is finally destroyed. This method is called just before the component is removed from the DOM.

Interfaces

We can define the lifecycle hook methods directly on the component class, but we can aslo use the advantage of the interface, since each of these lifecycle hook methods has an associated TypeScript interface. The name of those interfaces is the same name as the method, just without the ng prefix. For example, ngOnInit has an interface called OnInit. Each interface defines just one lifecycle hook method. One more important note is that the browser-based TypeScript compiler does not raise a compilation error when we don’t implement interface functions in our class. But, in the compiling time of TypeScript code, it will throw an error.

import {

    OnChanges,

    OnInit,

    DoCheck,

    AfterContentInit,

    AfterContentChecked,

    AfterViewInit,

    AfterViewChecked,

    OnDestroy

} from '@angular/core';

class SampleComponent implements

    OnChanges,

    OnInit,

    DoCheck,

    AfterContentInit,

    AfterContentChecked,

    AfterViewInit,

    AfterViewChecked,

    OnDestroy {

  ...

}


Sample code of app.component.lifecycle.ts

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'lifecycle-sample',
    templateUrl: 'app.component.lifecycle.html'
})

export class LifeCycleComponent {    
    data:number=100;

    constructor() {
        console.log(`new - data is ${this.data}`);
    }

    ngOnChanges() {
        console.log(`ngOnChanges - data is ${this.data}`);
    }

    ngOnInit() {
        console.log(`ngOnInit  - data is ${this.data}`);
    }

    ngDoCheck() {
        console.log("ngDoCheck")
    }

    ngAfterContentInit() {
        console.log("ngAfterContentInit");
    }

    ngAfterContentChecked() {
        console.log("ngAfterContentChecked");
    }

    ngAfterViewInit() {
        console.log("ngAfterViewInit");
    }

    ngAfterViewChecked() {
        console.log("ngAfterViewChecked");
    }

    ngOnDestroy() {
        console.log("ngOnDestroy");
    }

    fnAddNumber():void{
        this.data+=100;
    }

    deleteNumber():void{
        this.data -=10;
    }
}


Sample code of app.component.lifecycle.html

    <span class="setup">Given Number</span>
    <h1 class="punchline">{{ data }}</h1>

  <button type="button" class="btn btn-success"
          (click)="fnAddNumber()">Add NUmber
  </button>
  <button type="button"
          class="btn btn-danger"
          (click)="deleteNumber()">Clear Number
  </button>


Output Result

Result


If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8.

AngularJS Event Hook

Published at DZone with permission of Debasis Saha, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Power of @ngrx/signalstore: A Deep Dive Into Task Management
  • How To Make a Windows Keylogger By Yourself
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Code Play #1: WebSockets With Vert.x and Angular

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!