簡體   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