![](/img/trans.png)
[英]How to pass value from one component to another component in 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而不是的更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.