Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a Tag Dynamically? Angular 2

Tags:

angular

Is there anyway to change this:

<div>Some text here</div>

To:

<tr>Some text here</tr>

Change the tag DIV tag to TR tag dynamically? Basically Replace the Tags?

like image 810
edumas000 Avatar asked Feb 05 '17 05:02

edumas000


2 Answers

We can use Grochni's approach to provide us a dynamic html element container using ng-template.

<ng-container [ngTemplateOutlet]="showTr ? tr : div" [ngTemplateOutletContext]="{ $implicit: content }">
</ng-container>
<ng-template #content>
  Some text here
</ng-template>

<ng-template #tr let-content>
  <tr><ng-container [ngTemplateOutlet]="content"></ng-container></tr>
</ng-template>

<ng-template #div let-content>
  <div><ng-container [ngTemplateOutlet]="content"></ng-container></div>
</ng-template>
like image 123
Pedram A. Keyvani Avatar answered Oct 15 '22 16:10

Pedram A. Keyvani


Here is another way to avoid duplication. I needed to use a different tag depending on some condition:

Create template which both tags will use:

<ng-template #tagTemplate>
      <h1>Hello and Hi</h1>
      <p>Bye</p>
</ng-template>

Define both tags and use ngIf. The content of the tags will be the template created above.

<div class="post-widget" *ngIf="data">
    <ng-container *ngTemplateOutlet="tagTemplate;"></ng-container>
</div>

<ion-content class="post-widget" *ngIf="!data">
    <ng-container *ngTemplateOutlet="tagTemplate;"></ng-container>
</ion-content>
like image 44
Sumama Waheed Avatar answered Oct 15 '22 14:10

Sumama Waheed