Angular lifecycle hooks: ngAfterViewInit vs ngAfterContentInit

💡 **Frontend Interview Question for Angular Developer** **Q23:- What is the difference between `ngAfterViewInit()` and `ngAfterContentInit()`?** --- ### 🔹 ngAfterViewInit() → Called **after Angular initializes the component’s view** and child views. → Used with `@ViewChild` to access elements inside the component template. ```typescript @ViewChild('myDiv') div!: ElementRef; ngAfterViewInit() { console.log(this.div.nativeElement.textContent); } ``` --- ### 🔹 ngAfterContentInit() → Called **after Angular projects external content** (from a parent) into the component using `<ng-content>`. → Used with `@ContentChild` to access projected content. ```typescript @ContentChild('contentPara') para!: ElementRef; ngAfterContentInit() { console.log(this.para.nativeElement.textContent); } ``` --- ✅ **Key Difference:** `ngAfterViewInit()` → Access your own view elements. `ngAfterContentInit()` → Access parent-projected content. --- #Angular #FrontendDevelopment #AngularInterview #WebDevelopment #TypeScript #AngularTips #CodingCommunity

To view or add a comment, sign in

Explore content categories