Tanu Pawar
Tanu Pawar

Reputation: 29

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)

So consumer component will use CardComponent selector and pass both dataArray and Template.

How can i achieve it? (passing htmltemplate)

Upvotes: 2

Views: 4299

Answers (2)

Chetan Laddha
Chetan Laddha

Reputation: 1007

Yes, it is possible to pass HTML template using the ng-content approach but you should always go via template approach.

Your .html file -> Generic ->

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

Your .ts file

    @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

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

Upvotes: 3

Shan Krishnan
Shan Krishnan

Reputation: 1

You can use ng-content tag.

Your reusable component (YOUR-REUSABLE-COMPONENT) template is something like this.

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

Upvotes: 0

Related Questions