ngTemplateOutlet: templateRef.createdEmbeddedView не является функцией

Я пытаюсь создать модульную таблицу.

Для этого я использую ссылки на шаблоны и контейнеры 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;
  }
}

Редактировать

Я попытался поместить шаблон за пределы селектора таблицы и передать его как ввод в таблицу, и, похоже, он работает. Разве вы не можете использовать дочерние элементы контента для этого?


person Community    schedule 10.05.2019    source источник


Ответы (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>

person connectedMind    schedule 02.10.2019
comment
Спасибо за ответ, но было бы полезно объяснить решение в дополнение к предоставлению кода - person Raghu; 25.06.2020