angularfrontendng-content

Angular conditional content projection, use of ng-container


I am following the official Angular documentation and on the conditional content projection section, There is a code snippet:

    <div *ngIf="expanded" [id]="contentId">
        <ng-container [ngTemplateOutlet]="content.templateRef"></ng-container>
    </div>

I couldn't understand why there is a need of div here. Can't we just assign the ngIf directive and id property on ng-container?


Solution

  • Angular's ng-container is a special syntax (logical) element, it's not a regular html element, nor a component or class. Since it's not an element, it doesn't render in the DOM (although its content does, if criteria is met), so it cannot be referenced for styling or javascript DOM manipulation - it's used for logical organization/grouping of nodes. It appears in DOM like a comment and you cannot access it, thus the id attribute is lost on it and does nothing.

    Furthermore, if we leave id on div and move ngIf to container, the div will certainly be rendered (even if empty) inside the DOM, but in this case we want it rendered only if condition is met.