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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With