如何解决如何使ngTemplateOutlet在角度上动态
这是我尝试过的代码: HTML
<ng-container [ngTemplateOutlet]="room"></ng-container>
<ng-template #room1>
test 1
</ng-template>
<ng-template #room2>
test 2
</ng-template>
<ng-template #room3>
test 3
</ng-template>
TS
room = 'room1';
我想做的是显示基于变量的模板。
room = 'room1'
,则仅显示模板#room1
。
但是我遇到了一个错误:Error: templateRef.createEmbeddedView is not a function
解决方法
将它们添加到您的component.ts
文件中
@ViewChild('room1',{ static: false }) room1:TemplateRef<any>;
@ViewChild('room2',{ static: false }) room2:TemplateRef<any>;
@ViewChild('room3',{ static: false }) room3:TemplateRef<any>;
有关更多详细信息,check this answer
,您可以通过在ngTemplateOutlet
中添加条件来做到。您可以尝试以下三种方法之一:
方法1
<ng-container [ngTemplateOutlet]="room === 'room1' ? room1 : room === 'room2' ? room2 : room3"></ng-container>
方法2:
HTML
<ng-container [ngTemplateOutlet]="selectedRoom"></ng-container>
组件
@ViewChild('room1') room1: TemplateRef<any>;
@ViewChild('room2') room2: TemplateRef<any>;
@ViewChild('room3') room3: TemplateRef<any>;
room = 'room1';
get selectedRoom() {
const rooms = {
room1: this.room1,room2: this.room2,room3: this.room3
}
return rooms[this.room];
}
方法3(与方法2相同,但使用条件方法):
HTML
<ng-container [ngTemplateOutlet]="selectedRoom"></ng-container>
组件
...
get selectedRoom() {
return this.room === 'room1'
? this.room1
: this.room === 'room2'
? this.room2
: this.room3;
}
随函附上 Stackblitz Demo 供您参考
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。