Angular2 ngSwitch with <template> only

Hendrik picture Hendrik · Jun 9, 2016 · Viewed 36.3k times · Source

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

Answer

Ismail H picture Ismail H · Jan 4, 2017

That is now supported since the final release. The following code can be applied to your example :

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

See documentation for more info