Angular Component Lifecycle Hooks:

Angular Component Lifecycle Hooks:

Angular Component Lifecycle Hooks:


let me tell you about Angular Lifecycle Hooks — they’re like a series of events that happen when an Angular component is created, run, or destroyed. Think of it like a party — you have the setup, the party itself, and then the cleanup.


Each of these events is like a checkpoint where you can keep track of what’s going on with the component, like changing its state or interacting with other components or services. You can use these events to do all sorts of cool things to make your component work better.


These hooks are implemented in Angular components using a pre-defined interface that tells the component which event to trigger and when to call its method automatically. It’s like a dance routine — you just have to follow the steps.


Using these hooks helps ensure that your Angular component runs smoothly and efficiently. Each event has a specific purpose and tells your component what it should do at that point in time. This helps make your app faster and more responsive, which is always a good thing for user experience.


So yeah, Angular Lifecycle Hooks are a powerful tool in your developer toolbox that you can use to make your app work better and smoother. Let’s examine these hooks in order of call with examples.


1. ngOnChanges: This method is a lifecycle hook in Angular that is invoked every time there is a change in one of the input properties of the component. This means that the method is triggered whenever Angular sets a data-bound input property. Its main purpose is to allow the developer to detect and respond to changes to input properties in the component.


Note: Keep in mind that it will be called with every change, which will negatively affect performance!


import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnChanges {
  @Input() userData: any;
  profileImageUrl: string;

  ngOnChanges() {
    if (this.userData.age < 18) {
      this.profileImageUrl = 'path/to/youthful-image.png';
    } else {
      this.profileImageUrl = 'path/to/professional-image.png';
    }
  }
}


In this example, ngOnChanges() hook is called every time there is a change to the userData input property. If the user is under 18, the component sets the profileImageUrl path for the youthful image. If the user is 18 or over, it sets the profileImageUrl path for the professional image.


2. ngOnInit: This method is a lifecycle hook that is called once after the ngOnChanges method, and it is invoked when the component has been initialized. Since ngOnInit runs after the constructor method, all injected dependencies will be resolved and all class members will be defined. Therefore, it is an ideal place to perform any necessary initialization work or logic for the component.


import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {

  data: any;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.data = data;
    });
  }

}


In the example above, ngOnInit()hook uses a dataServiceto get the data. This method runs only once during the initial loading of the component and is used to initialize the state of the component.


3. ngDoCheck: This method is another lifecycle hook in Angular and it is invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.

This hook detects and acts upon every change that Angular can’t find automatically. It gets called before ngOnChanges() and ngOnInit() methods.


import { Component, Input, DoCheck } from '@angular/core';

@Component({
  selector: 'app-user',
  template: '{{ user.name }}'
})
export class UserComponent implements DoCheck {
  @Input() user: any;
  private previousName = '';

  ngDoCheck() {
    if (this.user.name !== this.previousName) {
      console.log(`User name changed from ${this.previousName} to ${this.user.name}`);
      this.previousName = this.user.name;
    }
  }
}


In this example, ngDoCheck()hook keeps track of the name property of the component’s user property and prints a message using console.log() when that property changes.


ngDoCheck() is useful when you want to keep track of properties manually. However, calling this method frequently can cause performance issues. Therefore, this hook should be used as little as possible.


4. ngAfterContentInit: This is a lifecycle hook in Angular that is called after Angular initializes the content projected into the component. It is a good place to perform initialization that relies on content initialization.


For example, let’s consider an example of a blog post component that receives comments from its parent component. The comments are passed as content through the component’s transclusion slot. We want to display the number of comments in the blog post component’s template.


In this case, we can use the ngAfterContentInit() lifecycle hook to get the comments from the transcluded content and display the count in the template.

Here’s how the code would look like:


import { Component, AfterContentInit, ContentChildren, QueryList } from '@angular/core';
import { CommentComponent } from './comment.component';

@Component({
  selector: 'app-blog-post',
  template: `
    <h1>{{ title }}</h1>
    <div class="content" [innerHTML]="content"></div>
    <h2>{{ comments.length }} Comments</h2>
    <ng-content></ng-content>
  `
})
export class BlogPostComponent implements AfterContentInit {
  @ContentChildren(CommentComponent) comments: QueryList<CommentComponent>;

  title = 'My Blog Post';
  content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit...';

  ngAfterContentInit() {
    // Get the comments from the transcluded content
    console.log(this.comments.toArray());
  }
}


In the above example, we use the @ContentChildren decorator to get a reference for all the CommentComponent instances that are transcluded into the BlogPostComponent. We then use the length property of the QueryList to display the count of comments in the template.


5. ngAfterContentChecked: This is a lifecycle hook in Angular that gets called after every change detection cycle when the component’s content has been checked. It is called after ngAfterContentInit() and every subsequent ngOnChanges() lifecycle hook.


This hook is useful when you need to perform additional checks or operations after Angular updates the component’s content.


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

@Component({
  selector: 'app-example',
  template: `
    <div *ngIf="show">
      <h1>{{ title }}</h1>
      <p>{{ content }}</p>
    </div>
  `,
})
export class ExampleComponent implements AfterContentChecked {
  title = 'Example';
  content = 'This is an example of ngAfterContentChecked() hook';
  show = false;

  ngAfterContentChecked() {
    console.log('ngAfterContentChecked() called.');
  }

  toggle() {
    this.show = !this.show;
  }
}


In below example, there is a component that displays a title and content when show is truengAfterContentChecked() hook logs a message to the console every time it is called. When the component is rendered, ngAfterContentChecked() will be called after ngAfterContentInit() and will log a message to the console. If the user calls the toggle() method to change the value of show, the component's content will be re-checked and ngAfterContentChecked() will be called again, logging another message to the console.


6. ngAfterViewInit: This is a lifecycle hook that is called after the component has been placed in the view tree and the content view and view have been fully rendered.


ngAfterInitView() method provides a point for code to be executed after the component has been created. For example, if you need to select a DOM element in your component, or if you need to make an external library interact with your component, you can use this method.


import { Component, AfterViewInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: '<p #myElement>Hello, World!</p>'
})
export class MyComponent implements AfterViewInit {
  constructor(private elRef: ElementRef) {}

  ngAfterViewInit() {
    // select myElement
    const myElement = this.elRef.nativeElement.querySelector('p');
    // changing properties
    myElement.style.color = 'red';
  }
}


In below example, the ngAfterViewInit() method is used to select the myElementDOM element and change its style properties. This can be used for any work that needs to be done after the component has been created.


7. ngAfterViewChecked: This is a lifecycle hook that is used to check for changes in a component’s views and respond appropriately. This method is called when all views in the component view tree have been modified or when data in the component view has changed.


For example, consider a list component that displays a list of child items dynamically within a parent component. If each child item is a separate component, the ngAfterViewChecked() method can be called for changes made in the child components. This ensures that the necessary changes are made for each component, enabling all components to be displayed correctly.


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

@Component({
  selector: 'app-example',
  template: `
    <div>
      {{ title }}
      <button (click)="changeTitle()">Change Title</button>
    </div>
  `
})
export class ExampleComponent implements AfterViewChecked {
  title = 'Initial Title';

  ngAfterViewChecked() {
    console.log('ngAfterViewChecked is called!');
  }

  changeTitle() {
    this.title = 'New Title';
  }
}


In below example, the ngAfterViewChecked() method is called whenever there is a change in the component’s view and prints a message to the console. changeTile()method changes the title within the component and triggers ngAfterViewChecked() method to be called again.


Note:ngAfterViewChecked() method can be called frequently and can have a negative impact on performance since it tracks any changes in the component content. It is recommended to avoid unnecessary use of this method.


8. ngOnDestroy: This is a lifecycle hook that is invoked just before Angular destroys the component. You can use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.


import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-my-component',
  template: '<p>My Component</p>',
})
export class MyComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    this.subscription = someObservable.subscribe(() => {
      // do something
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}


In below example, we have a component called MyComponent that subscribes to an observable in its constructor. To avoid memory leaks and ensure that the subscription is properly cleaned up when the component is destroyed, we use ngOnDestroy() to unsubscribe from the observable. This way, we prevent any further updates to the component after it has been destroyed, avoiding any potential errors.



Relevant Information:


In an era defined by digital transformation, businesses strive to stand out and reach their target audience in unique and engaging ways. One company at the forefront of this innovation is Angrio Technologies, an emerging tech powerhouse that's setting a new standard in the world of technology with its cutting-edge front-end solutions.


At Angrio Technologies, the team understands that a company's website is often the first touchpoint for potential customers. Angular, a powerful front-end framework, empowers Angrio's developers to create robust and responsive web applications that not only load quickly but provide a seamless and engaging user experience.


By creating robust web applications and cross-platform mobile apps, Angrio elevates technology performance and drives engagement to new heights. so visit now


More content at AngrioTechnologies.

Follow us on TwitterLinkedIn

Follow me on  LinkedIn



Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts