Elykov Alexandr
Elykov Alexandr

Reputation: 85

Choose angular template by variable

I have 3 different <ng-template>s. My component holds the switching variable with the name of template I want to render. How to inject it into my page?

Upvotes: 1

Views: 1100

Answers (2)

Himanshu Singh
Himanshu Singh

Reputation: 2165

You can do it the following way of course from the following code you have to replace <div> with your <ng-template>

<div [ngSwitch]="yourValue">
    <div *ngSwitchCase="'hello'">hello</div>
    <div *ngSwitchCase="'world'">world</div>
    <div *ngSwitchDefault>default</div>
</div>

This is the : working example

UPDATE: working link corrected.

Upvotes: 1

Reactgular
Reactgular

Reputation: 54771

You can use an object to hold references to the templates, and then just refer to that object's property by the string value.

@Component({
   template: `
   <ng-container *ngIf="{One:One,Two:Two,Three:Three} as templates">
       <ng-container *ngTemplateOutlet="templates[name]"></ng-container>
   </ng-container>
   <ng-template #One>ONE</ng-template>
   <ng-template #Two>TWO</ng-template>
   <ng-template #Three>THREE</ng-template>
   `
})
export class ExampleComponent {
   public name = 'One';
}

Upvotes: 1

Related Questions