【问题标题】:ngTemplateOutlet : templateRef.createdEmbeddedView is not a functionngTemplateOutlet : templateRef.createdEmbeddedView 不是一个函数
【发布时间】:2019-09-28 01:16:02
【问题描述】:

我正在尝试创建一个模块化表。

为此,我使用模板引用和 ng 容器。

我做了这个 stackblitz,非常简单:

https://stackblitz.com/edit/angular-2xhely

运行的时候报错

TypeError: templateRef.createEmbeddedView 不是函数

而且我已经上网一段时间了,似乎无法找到解决我的问题的方法。

这里是相关代码。

指令

import { Directive, Input, TemplateRef } from '@angular/core';
@Directive({ selector: '[template]' })
export class TemplateDirective {
  @Input() template: string;
  constructor(public templateRef: TemplateRef<any>) { }
}

根组件

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
<app-table [data]="data">
  <ng-template template="body" let-item>
    <td>{{item.id}}</td>
    <td>{{item.nom}}</td>
  </ng-template>
</app-table>`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  data = [{ id: 1, nom: 'Max' }];
}

表格组件

import { Component, OnInit, Input, ContentChildren, QueryList } from '@angular/core';
import { TemplateDirective } from './template.directive';
@Component({
  selector: 'app-table',
  template: `
<table>
  <thead>
    <td>ID</td>
    <td>NOM</td>
  </thead>
  <tbody *ngIf="template">
    <ng-container *ngFor="let item of data">
      <ng-container *ngTemplateOutlet="template; context: { $implicit: item }">
      </ng-container>
    </ng-container>
  </tbody>
</table>
`,
  styleUrls: ['./table.component.css']
})
export class TableComponent {
  @Input() data: any[];
  @ContentChildren(TemplateDirective) templates: QueryList<any>;
  template: TemplateDirective;

  ngAfterContentInit() {
    this.template = this.templates.first.template;
  }
}

编辑

我尝试将模板放在表格选择器之外并将其作为表格的输入提供,它似乎可以工作。是不是您不能使用内容儿童来做到这一点?

【问题讨论】:

    标签: angular typescript angular-dynamic-components


    【解决方案1】:

    如果您将 TableComponent 更新为此,它可以工作。希望这能解决您的问题。

    <table>
    	<thead>
    		<td>ID</td>
    		<td>NOM</td>
    	</thead>
    	<tbody *ngIf="template">
        <tr>
          <ng-container *ngFor="let item of data"
                        [ngTemplateOutlet]="template"
                        [ngTemplateOutletContext]="{ $implicit: item }">
          </ng-container>
        </tr>
    	</tbody>
    </table>
    
    <ng-template #template let-item>
    <td>{{item?.id}}</td>
    <td>{{item?.nom}}</td>
    </ng-template>

    【讨论】:

    • 感谢您的回答,但除了提供代码之外,解释解决方案会很有用
    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2016-07-08
    • 2013-03-03
    • 2022-01-09
    • 2018-03-12
    • 2017-08-17
    • 2017-09-22
    • 2018-12-16
    相关资源
    最近更新 更多