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
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.
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.
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.
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With