通过输入调用模板名称

时间:2019-08-28 21:02:54

标签: angular viewchild ng-template

假设我在一个组件中有多个btn-group变体,并希望将它们分组为模板。在父元素中,我想通过注入字符串(模板名称)来调用这些模板。那就是我所做的:

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])

是否有更好的方法来执行此操作,或者通常这种模式是不好的做法?

1 个答案:

答案 0 :(得分:0)

可以通过*ngTemplateOutlet指令处理多个模板,该指令期望引用ViewChild

<ng-container *ngTemplateOutlet='currentTemplate'></ng-container>

get currentTemplate(){if(some-condition) {return this.mode1} else {return this.mode2} }