【问题标题】:Angular 7 - ngTemplateOutlet Variable Value (Expression)Angular 7 - ngTemplateOutlet 变量值(表达式)
【发布时间】:2020-06-29 12:49:51
【问题描述】:

我无法通过变量在我的 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

【问题讨论】:

    标签: angular ng-container


    【解决方案1】:

    对于这样的用例,您首先必须通过ViewChild 查询捕获定义的模板,幸运的是它还支持TemplateRef

    摘自angular.io

    查看孩子

    配置视图查询的属性装饰器。

    支持以下选择器。

    • ...

    • 一个 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>
    

    【讨论】:

    • 谢谢,这正是我所需要的
    猜你喜欢
    • 2017-02-17
    • 2018-12-12
    • 1970-01-01
    • 2019-06-30
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多