如何在 Angular 中创建具有两个或更多内容占位符的容器组件?

How can I create a container component with two or more content placeholders in Angular?

我必须开发一个类似于这个的可重用组件:

它有两个容器部分,可以容纳当时未知的其他组件,主要内容部分和菜单部分:

谷歌搜索,我找到了一个使用ng-content指令的example,但我不知道它是否可以多次使用(这是我第一次使用Angular 一个项目)。这是想法:

<!-- WindowComponent -->
<div class="window">
    <h4>Window title</h4>
    <ng-content></ng-content>
</div>

<!-- Content -->
<div class="content">
    <app-window>
        <div>Some content</div>
    </app-window>

    <!-- How about the menu? -->
</div>

是的,您可以在一个组件中多次使用。 如果需要,您可以将视图分成几个部分。

  • 容器组件

  • 菜单组件

  • Graphs/Content分量

并且您可以将菜单组件和图形组件放入容器组件的模板中。

您可以将 <ng-content> 与 select 一起使用。像这样:

import { Component } from '@angular/core';

@Component({
  selector: 'transclude',
  template: `

  <header>
    <ng-content select=".header"></ng-content>
  </header>

  <main>
    <ng-content select=".main"></ng-content>
  </main>

  <footer>
   <ng-content select=".footer"></ng-content>
  </footer>

  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class TranscludeComponent  {
}

用法:

<transclude>
  <div class="header">Header</div>
  <div class="main">Main</div>
  <div class="footer">Footer</div>
</transclude>

Live demo

<ng-content select="..."> 通过以下方式支持 selecting:

  • css 类 <ng-content select=".my-css-class">
  • ng 指令 ​​<ng-content select="[my-directive]">
  • ng 组件 <ng-content select="my-component">