ngAfterContentInit

ngAfterContentInit

ngAfterContentInit is a lifecycle hook in Angular that is called once after the component’s projected content (i.e., content inserted using <ng-content>) has been fully initialized.

 

When Is It Triggered?

  • Triggered only once after Angular projects external content into the component's view using <ng-content>.

Common Use Cases:

  1. Accessing Projected Content
    • Use @ContentChild or @ContentChildren to reference and interact with elements/components projected into the component.
  1. Logic Based on Projected Content
    • Perform setup tasks such as validation or initializing internal state based on the content.
  1. Dynamic Behavior or Styling
    • Customize appearance or behavior dynamically depending on the presence or nature of projected content.
  1. Custom Form Validation
    • Register and validate form controls that are projected into reusable components.
  1. Reusable Component Design
    • Essential for creating flexible components like modals, tabs, dropdowns that render external content.

Important Notes:

  • It runs only once, unlike ngAfterContentChecked, which runs on every change detection.
  • It's applicable only when using <ng-content>.
  • Avoid direct DOM manipulation unless necessary (prefer Angular template references and directives).

Example:

Parent Component:

<app-alert>

  <p #projectedRef>This is an important alert!</p>

</app-alert>

Child Component (with ng-content):

@Component({

  selector: 'app-alert',

  template: `<div class="alert-box"><ng-content></ng-content></div>`,

  styles: [`.alert-box { border: 1px solid red; padding: 10px; }`]

})

export class AlertComponent implements AfterContentInit {

 

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

 

  ngAfterContentInit() {

    console.log('Projected content:', this.content.nativeElement.textContent);

    this.content.nativeElement.style.fontWeight = 'bold';

  }

}


Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular