1

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?

7
  • 2
    I think you are going at it the wrong way. Why would you want to use different element tags? Perhaps there is another way to what issue you want to overcome with your "different elements" Commented Dec 4, 2020 at 9:21
  • This sounds like something you should solve using css, for example by setting a class on a root element and saying that all direct children should be display: inline if you want them to behave as spans Commented Dec 4, 2020 at 9:38
  • I've created a stackblitz showing a possible approach. Keep in mind that you do need an anchor (a dom element) to insert elements, so a "container" is nescessary Commented Dec 4, 2020 at 9:43
  • @MikeS. - Thank you this works. But it is kind of un-angularic to directly manipulate the DOM, you are working against the framework. I`m not even sure, it variables inside the container would be interpreted. Commented Dec 4, 2020 at 9:54
  • @ShamPooSham, @Poul Kruijt - Yes, you normally don`t need this, and can work with ng-template or css. But in some cases, it would be great to have it. I have such a case. Commented Dec 4, 2020 at 9:56

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

You either have to add an extra block of logic in a complicated directive or add a simple block of html in your component. I'd say this is probably the right approach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.