Search code examples
angularangular-lifecycle-hooks

Why we use - ngAfterContentInit lifecycle method


I am learning angular.There are a lot of lifecycle methods. For example ngOnChanges runs every time where is new value in the input properties in the child component - that are passed by value.

I don't understand the method - ngAfterContentInit. In angular documentation says :

https://angular.io/guide/lifecycle-hooks

Respond after Angular projects external content into the component's view, or into the view that a directive is in.

But that does'n seem as good explanation. Can somoebody please tell my why we use and to understand better one REAL WOLRD SCENARIO - USE CASE


Solution

  • there is a possibility of content projection in angular

    // my-container-component.template
    <header>
     this is my container
    </header>
    <main>
       <span> it contains something passed from outside </span>
       <ng-content></ng-content>
    </main>
    

    usage:

     <my-container><span>something that will be rendered be INSIDE of the component</span></my-container>
    

    the span will be rendered in place of ng-content element inside of a component. this passed piece of html is usually called "content" in angular. so ngAfterContentInit() is a good hook to interact with this content, if you need to