繁体   English   中英

我们可以将html模板从angular2中的一个组件传递到另一个组件吗?

[英]Can we pass html template from one component to another component in angular2?

假设我有一个可重用的基本组件CardComponent,即它将接受诸如1. DataArray 2. HTML模板(经过迭代)的输入。

因此,消费者组件将使用CardComponent选择器并传递dataArray和Template。

我该如何实现? (通过htmltemplate)

您可以使用ng-content标签。

您的可重用组件(YOUR-REUSABLE-COMPONENT)模板就是这样。

<div class="box">
    <ng-content></ng-content>
</div>

在其他组件模板中使用可重用组件

<YOUR-REUSABLE-COMPONENT>
<div class="class1">
<h1>my main component</h2>
</div>
</YOUR-REUSABLE-COMPONENT>

是的,可以使用ng-content方法传递HTML模板,但是您应该始终使用模板方法。

您的.html文件->通用->

<div>
      <ng-container *ngTemplateOutlet="template"> </ng-container>
 </div>

您的.ts文件

    @ContentChild(TemplateRef)
    template: TemplateRef<any>;

以及要传递模板的其他组件文件

<my-component>
     <ng-template> Your HTML Content </ng-template>
 </my-component>

有关为什么应考虑使用ng-template而不是的更多详细信息

https://medium.com/michalcafe/angulars-content-projection-trap-and-why-you-should-consider-using-template-outlet-instead-cc3c4cad87c9

Angular 2使用ng-content的“模板”在组件循环内使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM