[英]Can we pass html template from one component to another component in angular2?
Suppose i have a base component CardComponent which is resuable ie, it will accept input such as 1. DataArray 2. HTML template(that is iterated over) 假设我有一个可重用的基本组件CardComponent,即它将接受诸如1. DataArray 2. HTML模板(经过迭代)的输入。
So consumer component will use CardComponent selector and pass both dataArray and Template. 因此,消费者组件将使用CardComponent选择器并传递dataArray和Template。
How can i achieve it? 我该如何实现? (passing htmltemplate) (通过htmltemplate)
You can use ng-content tag. 您可以使用ng-content标签。
Your reusable component (YOUR-REUSABLE-COMPONENT) template is something like this. 您的可重用组件(YOUR-REUSABLE-COMPONENT)模板就是这样。
<div class="box">
<ng-content></ng-content>
</div>
Usage of your reusable component inside some other component template 在其他组件模板中使用可重用组件
<YOUR-REUSABLE-COMPONENT>
<div class="class1">
<h1>my main component</h2>
</div>
</YOUR-REUSABLE-COMPONENT>
Yes, it is possible to pass HTML template using the ng-content approach but you should always go via template approach. 是的,可以使用ng-content方法传递HTML模板,但是您应该始终使用模板方法。
Your .html file -> Generic -> 您的.html文件->通用->
<div>
<ng-container *ngTemplateOutlet="template"> </ng-container>
</div>
Your .ts file 您的.ts文件
@ContentChild(TemplateRef)
template: TemplateRef<any>;
and your other component files from where you want to pass the template: 以及要传递模板的其他组件文件 :
<my-component>
<ng-template> Your HTML Content </ng-template>
</my-component>
More details regarding why you should consider ng-template instead of 有关为什么应考虑使用ng-template而不是的更多详细信息
https://medium.com/michalcafe/angulars-content-projection-trap-and-why-you-should-consider-using-template-outlet-instead-cc3c4cad87c9 https://medium.com/michalcafe/angulars-content-projection-trap-and-why-you-should-consider-using-template-outlet-instead-cc3c4cad87c9
Angular 2 use a "template" for ng-content to use inside component loop Angular 2使用ng-content的“模板”在组件循环内使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.