【发布时间】:2019-08-28 21:02:54
【问题描述】:
假设我在一个组件中有多个 btn-groups 变体,并希望将它们分组为模板。在父元素中,我想通过注入字符串(模板名称)来调用这些模板。这就是我所做的:
app.component.html
<app-btn-commands mode="mode1"></app-btn-commands>
btn-commands.component.html
<div class="btn-commands">
<h1>title</h1>
<ng-container #entry></ng-container>
</div>
<ng-template #mode1>
<app-btn classes="btn--theme-alpha"></app-btn>
<app-btn></app-btn>
</ng-template>
<ng-template #mode2>
<app-btn classes="btn--theme-beta btn--size-10"></app-btn>
<app-btn classes="btn--theme-beta btn--size-10"></app-btn>
</ng-template>
btn-commmand.components.ts
export class BtnCommandsComponent implements AfterContentInit {
@ViewChild('mode1', {static: true}) mode1:TemplateRef<any>;
@ViewChild('mode2', {static: true}) mode2:TemplateRef<any>;
@ViewChild('entry', {read: ViewContainerRef, static: true}) entry: ViewContainerRef;
@Input()
mode;
constructor() {}
ngAfterContentInit() {
this.entry.createEmbeddedView(this[this.mode]);
}
}
代码正在运行,但我觉得这是一种非常老套的方法——尤其是这一行:
this.entry.createEmbeddedView(this[this.mode])
有没有更好的方法来做到这一点,或者这种模式通常是一种不好的做法?
【问题讨论】:
标签: angular viewchild ng-template