Posts

Showing posts from June 3, 2025

ngAfterViewChecked()

ngAfterViewChecked() When it's called: Runs  after ngAfterViewInit()  and  after every change detection cycle  involving the component's view and child views. Use case: For logic that must occur after the view has been rendered and checked. Useful when: Reacting to dynamic layout changes or view-related computations. Interacting with elements that might change after updates. Running animations or post-render updates. Performance & Caution: Since it runs  after every view check , avoid: Expensive operations inside it. Making changes that trigger further change detection (can cause infinite loops). Use ChangeDetectorRef or setTimeout() carefully if you must update the view.   Example 1: Simple DOM Dimension Check import { Component, AfterViewChecked, ViewChild, ElementRef } from '@angular/core'; @Component({   selector: 'app-after-view-checked-ex...

ngAfterViewInit()

ngAfterViewInit() When it's called: Invoked  once  after Angular fully initializes the component’s view and all child views. Occurs after the first ngAfterContentInit() and the view has been checked. Use case: Ideal for logic that depends on the DOM being fully rendered. Commonly used for: Initializing third-party libraries (e.g., jQuery, charting tools). Accessing and manipulating view elements via @ViewChild. Example: import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';   @Component({   selector: 'app-demo',   template: `<div #myDiv>Hello</div>` }) export class DemoComponent implements AfterViewInit {   @ViewChild('myDiv') divElement!: ElementRef;     ngAfterViewInit() {     console.log('ngAfterViewInit called');     this.divElement.nativeElemen...