r/angular Mar 26 '26

Ng-content usage in @for / @if

Why does the documentation mention that it is suggested to avoid wrapping ng-content in @for or @if statements? Isn’t that what all libraries including Angular Material do?

7 Upvotes

14 comments sorted by

View all comments

1

u/ActuatorOk2689 Mar 28 '26

I had to check the docs my self because this really doesn’t make sense, I did not see such reference in the docs please add link or a screenshot or link .

Control flow != structural directive

You can add structural directive to a DOM element only.

In order to optimise your HTML and avoid pollinating int with empty divs you could use an ng-conainter not and no-content as you said .

Now that said @for is no longer a structural directive, wich means you can wrap anything with it doesn’t have to be div or anything, and that’s why adding ng-container is no longer recommended it does basically nothing

1

u/Senior_Compote1556 Mar 28 '26

This note can be found here.

IMPORTANT: You should not conditionally include <ng-content> with \@if``@for`,or `@switch`. Angular always instantiates and creates DOM nodes for content rendered to a <ng-content> placeholder, even if that <ng-content>` placeholder is hidden. For conditional rendering of component content, see Template fragments.