Reputation:
I am trying to create a modular table.
To do that, I use template references and ng containers.
I have made this stackblitz, which is pretty simple :
https://stackblitz.com/edit/angular-2xhely
When ran, it says the error
TypeError: templateRef.createEmbeddedView is not a function
And I have looked online for a while now, and can't seem to find a solution to my issue.
Here is the related code.
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;
}
}
I have tried putting the template outside of the table selector and give it as in input to the table, and it seems to work. Would it be that you can't use content children to do that ?
Upvotes: 3
Views: 6586
Reputation: 439
If you update your TableComponent to this, it works. Hope this solves your problem.
<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>
Upvotes: 1