Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic tag based on value

Tags:

angular

I need to create a template where native html tags will be defined dynamically depending on a variable value.

I tried to used a custom directive that replaces the initially defined tag by the requested new one, such as described here. Although that solution seems to work to a certain extent, it breaks variables and events bindings of the innerHTML content with the Component Class. In other words, changes in the Component Class variables have no longer have effect on the rendered html.

In Vue there is a very simple way of implementing that:

<component :is="tagName" class="foo" style="color:red">
  anything inside component
</component>

where tagName = 'p' for example, which will result in

<p class="foo" style="color:red">
  anything inside component
</p>

I was wondering if there would be any similar solution in angular. Any help would be great.

like image 592
mrcl Avatar asked Mar 12 '26 03:03

mrcl


1 Answers

Why don't you just add the specified elements conditionally?

<container-element [ngSwitch]="tagName">  
  <elementType1 *ngSwitchCase="tagName1">...</elementType1>
  <elementType2 *ngSwitchCase="tagName2">...</elementType2>
  <elementTypeDefault *ngSwitchDefault>...</elementTypeDefault>
</container-element>

Or using a basic *ngIf:

<elementType1 *ngIf="tagName1_expression">anything inside component</elementType1>
<elementType2 *ngIf="tagName2_expression">anything inside component</elementType2>
like image 58
zhulien Avatar answered Mar 14 '26 18:03

zhulien