How can I create a container component with two or

2019-08-27 18:44发布

问题:

I have to develop a reusable component similar to this one:

It has two container parts that can hold other components unknown at the time, the main content part and the menu part:

Googling around, I have found an example that uses the ng-content directive, but I don't know if it can be used more than once or not (it's the first time I use Angular for a project). This is the idea:

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

回答1:

Yes you can use more than once in a component. You can break your view in to few components if needed.

  • Container component

  • Menu component

  • Graphs/Content component

And you can put menu component and the graphs component in to container component's template.



回答2:

You can use <ng-content> with select. Like this:

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

Usage:

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

Live demo

<ng-content select="..."> supports selecting by:

  • css classes <ng-content select=".my-css-class">
  • ng directives <ng-content select="[my-directive]">
  • ng component <ng-content select="my-component">