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

旧街凉风 提交于 2019-12-11 13:39:36

问题


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


来源:https://stackoverflow.com/questions/49648259/how-can-i-create-a-container-component-with-two-or-more-content-placeholders-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!