我正在尝试创建一个模块化的表格。
为此,我使用模板引用和ng容器。
我已经制作了这个很简单的stackblitz:
TypeError: templateRef.createEmbeddedView 不是一个函数
我已经在网上搜索了一段时间,似乎找不到解决方案。
以下是相关代码。
指令
为此,我使用模板引用和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;
}
}
编辑
我尝试将模板放在表选择器外面,并将其作为输入提供给表格,似乎可以工作。难道您不能使用内容子元素来实现这一点吗?