Angular 7 - ngTemplateOutlet 变量值(表达式)

Angular 7 - ngTemplateOutlet Variable Value (Expression)

我无法通过变量在我的 ng-container 中传递 *ngTemplateOutlet 的值。

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}}

当然,如果我在下面定义,一切都会按预期进行

<ng-container *ngTemplateOutlet="SingleSelect">

</ng-container>

如何使 SingleSelect 成为变量值?

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

对于这样的用例,您首先必须通过 ViewChild query which luckily also supports TemplateRef.

捕获定义的模板

摘自angular.io

ViewChild

Property decorator that configures a view query.

The following selectors are supported.

  • ...

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

注意 ng-template 'SingleSelect' 如何被捕获到下面的 templateComponentVar 中:

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>