Search code examples
htmlangularrenderingslotsng-content

What happens to empty ng-content fields


Simple question:

The Angular docs suggest not using ng-content in the case of conditional rendering on the component end:

If your component needs to conditionally render content, or render content multiple times, you should configure that component to accept an element that contains the content you want to conditionally render.

Using an element in these cases is not recommended, because when the consumer of a component supplies the content, that content is always initialized, even if the component does not define an element or if that element is inside of an ngIf statement. From: https://angular.io/guide/content-projection#conditional-content-projection

Does this apply to the consumers of component slots as well? For example:

<custom-table-component>
  <div ng-content-select-directive *ngIf="condition">
      This is a conditionally rendered element inhabiting an ng-content slot of a parent 
      component
  </div>
</custom-table-component>

Would the underlying ng-content-select still be rendered if the condition is falsy?


Solution

  • I tried to recreate the situation you describe in this stackblitz example

    From this it seems that the inner ng-content won't render in these cases if the condition is false.

    <div>
      <h1>Inner stuff here:</h1>
      <div style="border: 1px solid red">
        <app-custom-table-component>
          <div ng-content-select-directive *ngIf="false">
            This is a conditionally rendered element inhabiting an ng-content slot of a parent 
            component
        </div>
        </app-custom-table-component>
      </div>
    
    </div>
    

    And you can see that there is nothing in the DOM, but the debug info:

    enter image description here

    You can try to change the ngIf to true to see how it appears in the DOM (and the custom directive gets initialized as well, which won't if the ngIf is false)