【问题标题】:calling template name via input通过输入调用模板名称
【发布时间】: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


    【解决方案1】:

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

    <ng-container *ngTemplateOutlet='currentTemplate'></ng-container>
    
    get currentTemplate(){if(some-condition) {return this.mode1} else {return this.mode2} }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 2022-11-26
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多