空的 ng-content 字段会发生什么

What happens to empty ng-content fields

简单问题:

Angular 文档建议在 component end:

条件渲染的情况下不要使用 ng-content

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

这是否也适用于组件槽的消费者?例如:

<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>

如果条件为假,底层的 ng-content-select 是否仍会呈现?

我试图重现您在 this stackblitz example

中描述的情况

由此看来,如果条件为 false,内部 ng-content 将不会在这些情况下呈现。

<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>

你可以看到 DOM 中没有任何内容,但是调试信息:

您可以尝试将 ngIf 更改为 true 以查看它在 DOM 中的显示方式(自定义指令也会被初始化,如果ngIf 为假)