angularng-container

Angular 7 - ngTemplateOutlet Variable Value (Expression)


I am unable to pass the value of *ngTemplateOutlet in my ng-container via a variable.

app.component.ts

export class AppComponent  {
  templateName="SingleSelect";
}

app.component.html

<ng-container *ngTemplateOutlet="{{templateName}}">

</ng-container>

<ng-template #SingleSelect>
<p>Output from test template</p>
</ng-template>

{{templateName}}

Of course if I define below, everything works as expected

<ng-container *ngTemplateOutlet="SingleSelect">

</ng-container>

How can I make SingleSelect a variable value?

Stackblitz for reference- https://stackblitz.com/edit/angular-h4mgyq?file=src%2Fapp%2Fapp.component.html


Solution

  • For such a use case, you first have to capture the defined template via a ViewChild query which luckily also supports TemplateRef.

    Excerpt from angular.io

    ViewChild

    Property decorator that configures a view query.

    The following selectors are supported.

    • ...

    • A TemplateRef (e.g. query with @ViewChild(TemplateRef) template;)

    Notice how ng-template 'SingleSelect' is captured into a templateComponentVar below:

    app.component.ts

    import { Component, ViewChild, TemplateRef } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      @ViewChild('SingleSelect', { static: false }) templateComponentVar: TemplateRef<any>;
    }
    

    app.component.html

    <ng-container *ngTemplateOutlet="templateComponentVar"></ng-container>
    
    <ng-template #SingleSelect>
      <p>Output from test template</p>
    </ng-template>