这是我试图开始工作的代码(角度5):
import { Component, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
@Component({
selector: 'vcr',
template: `
<template #tpl>
<h1>ViewContainerRef</h1>
</template>
<div>Some element</div>
<div #container></div>
`,
})
export class VcrCmp {
@ViewChild('container', { read: ViewContainerRef }) _vcr;
@ViewChild('tpl') tpl: TemplateRef<any>;
constructor(
private viewContainerRef: ViewContainerRef
) {
}
ngAfterViewInit() {
console.info(this.viewContainerRef);
console.info(this._vcr);
this._vcr.createEmbeddedView(this.tpl);
this.viewContainerRef.createEmbeddedView(this.tpl);
}
}
问题是我遇到了这个(
templateRef.createEmbeddedView is not a function
)错误并且不太明白为什么。
此代码基于此示例https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682所以我想它应该可以工作。
我做错了什么?
根据 Angular 5 变更日志:
编译器选项enableLegacyTemplate现在默认被禁用,如下所示 该元素自 v4 起已被弃用。使用
相反。<ng-template>
所以你应该使用
ng-template
而不是 template
:
<ng-template #tpl>
<h1>ViewContainerRef</h1>
</ng-template>
或将
enableLegacyTemplate
设置为 true
:
platformBrowserDynamic().bootstrapModule(AppModule, { enableLegacyTemplate: true })
但你应该知道
enableLegacyTemplate 选项和
<template>
元素都将在 Angular v6 中删除。
就我而言,错误是由于我在
ngTemplateOutlet
之前忘记了*(星号)
在 *ngIf 中引用时,else 子句不能是任意组件,但必须是 ng-template。
例如,
在具有与此类似的源代码的组件中:
<div *ngIf="myCondition ; else elseSection"> <!-- ... --> </div> <div #elseSection> <!-- ... --> </div>
生成的源代码应如下所示:
<div *ngIf="myCondition ; else elseSection"> <!-- ... --> </div> <ng-template #elseSection> <!-- ... --> </ng-template>
对我来说,问题在于组件中的变量和 HTML 文件中的模板使用相同的名称。
在我的例子中,ngTemplateOutlet =“templateValue”名称被定义为跨组件的变量,使用唯一值解决了问题。
似乎很明显,但我错过了这一点。
在较新的版本(Angular 8+)中,如果在 Angular 需要模板时没有传递模板,则会抛出此错误。
<ng-container *ngIf="getTemplate(col) as template; else defaultColumn">
<ng-container *ngTemplateOutlet="template; context: {'cell': rowData[col.field]}"></ng-container>
</ng-container>
<ng-template #defaultColumn>
{{rowData[col.field]}}
</ng-template>
在上述情况下,您的
getTemplate
方法应返回实际模板或 null
,仅此而已。我正在这里返回指令班。因此出现错误。
就我而言,错误是由于我输入了
[ngTemplateOutlet]
而不是 [ngTemplateOutletContext]
然后
[ngTemplateOutlet]
出现了两次并导致了错误。
在我的例子中,我尝试使用
import
语句和 *ngComponentOutlet
延迟加载组件,但我使用 *ngComponentOutlet
而不是 *ngTemplateOutlet
。
一旦我解决了这个问题,它就像一个魅力。
就我而言,*ngIf 有问题。 检查 getTemplate(col) 是否返回可观察值或简单布尔值。 如果可以观察到,请检查是否初始化正确。
{ng-container *ngIf="getTemplate(col) 作为模板;else defaultColumn">