0

let's say i have several variations of btn-groups in a component and want to group these as templates. in the parent element i want to call these templates by injecting the string (template name). that's what i've done:

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

the code is working but i feel like it's a very hacky way of doing this - especially this line: this.entry.createEmbeddedView(this[this.mode])

is there a better way of doing this or is this pattern in general a bad practice?

kingmauri
  • 345
  • 1
  • 3
  • 9

1 Answers1

0

multiple templates can be handled thru the *ngTemplateOutlet directive which expects a reference to a ViewChild.

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

get currentTemplate(){if(some-condition) {return this.mode1} else {return this.mode2} }
iams0nus
  • 481
  • 3
  • 8