如何在 Angular 个子组件选择器之间传递内容

How to pass content in between Angular child component selectors

我正在尝试在 Angular 组件选择器中传递数据,就像在 Angular material 或 MD Bootstrap.Below 中所做的那样 Bootstrap.Below 是显示的简单 Angular Material 卡片的示例Card 中选择器之间的内容。

<mat-card>Simple card</mat-card>

输出会像这样image

我试图通过声明一个带有容器的子组件来复制相同的内容,内容应该放在子组件选择器之间。

child.component.html

<div class=container></div>

child.component.ts

@Component({
selector: 'app-container',
templateUrl: './container.component.html',
styleUrls: ['./container.component.css']
 })

parent.component.html

<app-container> I am inside the container </app-container>

这不像 Material 卡片那样工作,文本的 none 在被组件选择器包围时显示。

您应该使用 ng-content 使用 angular 内容投影。按如下方式使用它:

<div class=container>
  <ng-content></ng-content>
</div>

如果你想传递多个内容,你可以在ng-content中使用select属性来select一个特定的元素,使用标签名称,class名称或id名字.

app.component.html

<app-container> 
  <header>Welcome</header>
  <p class="message">Hi, how are you</p>
  <footer>Copyright</footer>
</app-container>

parent.component.html

<div class=container>
  <header>
   <ng-content select="header"></ng-content>
  </header>
  <section>
    <ng-content select="p.message"></ng-content>
  <section>
  <footer>
     <ng-content select="footer"></ng-content>
  </footer>
</div>