Search code examples
angularangular-template

Angular template: Use variable value as DOM element type


I have a component and would like to render it as div or span dynamically. So I defined an input variable elementType. Now I would like to render it in a template.

Pseudo code:

<{{elementType}}>Content of the element</{{elementType}}>

This does of course not work, it`s a template rendering error. I could of course do something like

<div *ngIf="elementType == 'div'">Content of the element</div>
<span *ngIf="elementType == 'span'">Content of the element</span>

But I have to repeat myself with this, and in a more complex real world example, this is a mess.

What is a good way of handling this requirement?


Solution

  • Ok, my solution with ngTemplate:

    <ng-template #inner>
        The complex inner part
    </ng-template>
    
    <div *ngIf="elementType == 'div'">
        <ng-container *ngTemplateOutlet="inner"></ng-container>
    </div>
    <span *ngIf="elementType == 'span'">
        <ng-container *ngTemplateOutlet="inner"></ng-container>
    </span>
    

    That`s ok, and I do not repeat myself, even if the inner part is complex. Disadvantage: If I would like the element to be p, h1 or whatever else, I always have to add a new line to the template.

    Better ideas which are able to fullfill the requirement without this limitation?