Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngSwitch with <template> only

Tags:

I would like to use ngSwitch to conditionally render some content, but I want that content to be the only thing to be rendered to the DOM. I'll illustrate with an example.

This is what I have currently:

<div [ngSwitch]="thing.name">     <template ngSwitchWhen="foo">         <div>FOOOOOO</div>     </template>     <template ngSwitchWhen="bar">         <div>BARRRR</div>     </template>     <template ngSwitchWhen="cat">         <div>CAT</div>     </template>¯     <template ngSwitchWhen="dog">         <div>DOG</div>     </template> </div> 

I'd like to change the parent element from a <div> to a <template> so only the most inner elements are actually inserted into the DOM. I suspect it is probably possible, because I know you can do something like that with ngFor, i.e.:

<template ngFor [ngForOf]="things" let-thing="$implicit"> 

However, I haven't been able to work out how I could get it to work on an ngSwitch

like image 531
Hendrik Avatar asked Jun 09 '16 06:06

Hendrik


People also ask

Can we use ng-template inside Ng-container?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.

Can we apply ngIf to ng-template?

the element onto which the structural directive ngIf was applied has been moved into an ng-template. The expression of *ngIf has been split up and applied to two separate directives, using the [ngIf] and [ngIfElse] template input variable syntax.

What is pTemplate in ng-template?

pTemplate is a custom-made directive by PrimeNG. Its purpose is to link a template defined by you (the user) to a container defined by the library (PrimeNG). That enables the user to provide a custom template that is displayed inside a component made by the library.


1 Answers

<ng-container [ngSwitch]="activeLayout">   <ng-container *ngSwitchCase="'layout1'" [ngTemplateOutlet]="template1"></ng-container>   <ng-container *ngSwitchDefault [ngTemplateOutlet]="defaultTemplate"></ng-container> </ng-container> 

This is my solution when I need to make a switch of different ng-template. I hope it works for you.

like image 196
mrodri Avatar answered Oct 27 '22 12:10

mrodri