【问题标题】:In Angular, how can I use template content inside a customer component or directive?在 Angular 中,如何在客户组件或指令中使用模板内容?
【发布时间】:2022-11-24 01:21:33
【问题描述】:

假设我有一个组件需要包装不同的内容集:

<div class="box-box"> ... content ... </div>

我不想将组件放在模板上并将输入传递给孩子,而是执行以下操作:

<my-big-box> ... content ... </my-big-box> 或者 <div myBigBox> ... content ... </div>

前者是首选。我看到类似的东西用角度组件完成,例如 ng-content 或材料 ui 组件。不确定 100% 这是如何实现的或使用什么“术语”来获得更好的理解。

任何朝着正确方向的推动都是值得赞赏的。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用 <ng-content> 将 HTML 内容投影到自定义组件中。

    假设这是您组件的模板:

    <!-- 'section' and it's value can be anything you like, 
      you will use that to reference the ng-content  -->
    <div class="box-box">
      <ng-content select="[section=header]"></ng-content>
    
      <!-- you can have an ng-content without  -->
      <ng-content></ng-content>
      <p>
        This it's Box Box
      </p>
      <ng-content select="[section=footer]"></ng-content>
    </div>
    

    然后你可以在其中投影内容,例如:

    <my-big-box>
      <h3 section="footer">this should be in the footer</h3>
      <h1>this it's inside ng-content</h1>
      <h3 section="header">this should be in the header</h3>
    </my-big-box>
    

    Stackblitz demo

    Angular's Content Projection documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2013-05-14
      • 1970-01-01
      • 2020-02-11
      • 2016-10-14
      • 2017-09-16
      相关资源
      最近更新 更多