【问题标题】:What happens to empty ng-content fields清空 ng-content 字段会发生什么
【发布时间】:2021-11-10 21:52:14
【问题描述】:

简单的问题:

Angular 文档建议不要在 component 端进行条件渲染的情况下使用 ng-content:

如果您的组件需要有条件地渲染内容,或多次渲染内容,您应该将该组件配置为接受包含您要有条件地渲染的内容的元素。

不建议在这些情况下使用元素,因为当组件的使用者提供内容时,该内容始终会被初始化,即使组件没有定义元素或该元素位于 ngIf 语句中。 来自: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 是否仍会被渲染?

【问题讨论】:

    标签: html angular rendering slots ng-content


    【解决方案1】:

    我试图重现你在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 为 false,则不会初始化)

    【讨论】:

    • 首先,感谢您启动一切并进行手动检查!我稍微改变了你的例子,以显示我的困惑所在(我的错——我解释得不够好)。见这里:stackblitz.com/edit/angular-ivy-ctbtrz?file=src/app/…。在 devtools 中,两者最终都没有显示 DOM 节点创建,所以我很好奇在组件内部和外部隐藏选择器是否都是一个坏主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多