ngTemplateOutlet: templateRef.createdEmbeddedView不是一个函数。

3
我正在尝试创建一个模块化的表格。
为此,我使用模板引用和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;
  }
}

编辑

我尝试将模板放在表选择器外面,并将其作为输入提供给表格,似乎可以工作。难道您不能使用内容子元素来实现这一点吗?

1个回答

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>


2
谢谢回答,但除了提供代码之外,解释解决方案也会很有帮助。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接