'Wrapping Angular content in conditional outter tags

I would like to create and Angular component that when I specify

<app-title level="1">some text</app-title>
<app-title level="2">some other text</app-title>

it generates

<h1>some text</h1>
<h2>some other text</h2>

I've tried

<h1 *ngIf="isLevel1"><ng-content></ng-content></h1>
<h2 *ngIf="!isLevel1"><ng-content></ng-content></h2>

but ng-content only renders in one of the tags, not both.

How can I make the content appear inside an h1 or h2 tag based on the level?



Solution 1:[1]

You could try using the select attribute of ng-content and getting rid of the *ngIf:

<h1><ng-content select="[level=1]"></ng-content></h1>
<h2><ng-content select="[level=2]"></ng-content></h2>

Solution 2:[2]

ng-template is the answer. First put the ng-content inside an ng-template. Then embed your template in both conditional tags.

<ng-template #contentTemplate><ng-content></ng-content></ng-template>
<h1 *ngIf="isLevel1"><ng-template [ngTemplateOutlet]="contentTemplate"></ng-template></h1>
<h2 *ngIf="!isLevel1"><ng-template [ngTemplateOutlet]="contentTemplate"></ng-template></h2>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JuanDeLasNieves
Solution 2 rettigcd