ngAfterContentChecked - Angular Lifecycle Hook

ngAfterContentChecked (Angular Lifecycle Hook)

ngAfterContentChecked is a lifecycle hook in Angular that is called after every change detection cycle, specifically for checking the projected content (i.e., content rendered via <ng-content>).
Unlike ngAfterContentInit (which runs only once), this hook is triggered repeatedly as Angular checks for updates in projected content.

When to Use ngAfterContentChecked:

Use this hook when:

  • You need to react to dynamic changes in projected content.
  • You want to monitor content inside <ng-content> for updates.
  • You want to perform logic after every content check (with caution due to potential performance issues).

Common Use Cases:

  1. Detecting Changes in Projected Content
    • Check if projected text, nodes, or elements have changed over time.
  2. Dynamic Layout or Styling Adjustments
    • Apply styles or trigger visual updates based on content changes.
  3. Syncing with Dynamic Inputs via <ng-content>
    • Update internal logic when a parent dynamically changes the projected content.
  4. Debugging Change Detection
    • Useful during development to trace content changes over time.

Important Notes:

  • This hook runs very frequently—avoid expensive computations inside it.
  • Do not modify data-bound properties during this phase. It may trigger Angular errors like:
    • ExpressionChangedAfterItHasBeenCheckedError
  • Commonly used with @ContentChild or @ContentChildren to interact with projected content.

Example:

Parent Component Template:

<app-alert>

  <p #projectedRef>This is a dynamic error message!</p>

</app-alert>

Child Component (AlertComponent):

import {

  AfterContentChecked,

  Component,

  ContentChild,

  ElementRef,

  Renderer2

} from '@angular/core';

 

@Component({

  selector: 'app-alert',

  template: `

    <div class="alert-box">

      <ng-content></ng-content>

    </div>

  `,

  styles: [`

    .alert-box {

      border: 1px solid red;

      padding: 10px;

      background-color: #ffe5e5;

    }

    .highlight-error {

      background-color: yellow;

    }

  `]

})

export class AlertComponent implements AfterContentChecked {

  @ContentChild('projectedRef') projectedContent!: ElementRef;

  private previousText = '';

 

  constructor(private renderer: Renderer2) {}

 

  ngAfterContentChecked() {

    const currentText = this.projectedContent?.nativeElement?.textContent;

 

    if (currentText && currentText !== this.previousText) {

      console.log('Projected content changed to:', currentText);

      this.previousText = currentText;

 

      if (currentText.includes('error')) {

        this.renderer.addClass(this.projectedContent.nativeElement, 'highlight-error');

      } else {

        this.renderer.removeClass(this.projectedContent.nativeElement, 'highlight-error');

      }

    }

  }

}

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular