Say in an Angular template I want to choose the location to render an embedded view ( <ng-template>
) based on some condition.
<ng-template #foo>
Hello World.
</ng-template>
<p *ngIf="isBar; else baz">
Bar: <!-- Want to insert #foo here, sometimes -->
</p>
<div #baz>
Baz: <!-- Want to insert #foo over here instead, other times -->
</div>
I've used the else
part of an *ngIf
to insert a template defined elsewhere. I could write *ngIf="false; else #foo"
to render the embedded view template, but I feel that shouldn't be necessary.
<p *ngIf="isBar; else baz">
Bar: <ng-container *ngIf="false; else foo"></ng-container>
</p>
<div #baz>
Baz: <ng-container *ngIf="false; else foo"></ng-container>
</div>
You're looking for NgTemplateOutput
which "Inserts an embedded view from a prepared TemplateRef
."
https://angular.io/api/common/NgTemplateOutlet
<ng-template #foo>
Hello World.
</ng-template>
<p *ngIf="isBar; else baz">
Bar: <ng-container *ngTemplateOutlet="foo"></ng-container>
</p>
<div #baz>
Baz: <ng-container *ngTemplateOutlet="foo"></ng-container>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.