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

问题描述 投票:0回答:1

我试图在Angular组件选择器中传递Data,例如在Angular材质或MD 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卡那样工作,当组件选择器包含它时,不会显示任何文本。

html angular angular-directive angular-components
1个回答
1
投票

你应该使用ng-content使用角度内容投影。使用方法如下:

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

如果要传递多个内容,可以使用select中的ng-content属性,使用标记名称,类名称或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>
© www.soinside.com 2019 - 2024. All rights reserved.