Angular 7 - значение переменной ngTemplateOutlet (выражение) - PullRequest
0 голосов
/ 18 марта 2020

Я не могу передать значение * ngTemplateOutlet в моем ng-контейнере через переменную.

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

1 Ответ

1 голос
/ 18 марта 2020

Для такого варианта использования сначала необходимо получить определенный шаблон с помощью запроса ViewChild , который, к счастью, также поддерживает TemplateRef .

Выдержка из angular .io

ViewChild

Декоратор свойств, который настраивает запрос представления.

Поддерживаются следующие селекторы.

  • ...

  • TemplateRef (например, запрос с шаблоном @ViewChild (TemplateRef);)

Обратите внимание, как 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>
...