Angular 角度5:templateRef.createEmbeddedView不是函数

Angular 角度5:templateRef.createEmbeddedView不是函数,angular,angular2-template,Angular,Angular2 Template,下面是我试图使用的代码5: import { Component, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core'; @Component({ selector: 'vcr', template: ` <template #tpl> <h1>ViewContainerRef</h1> </template> <di

下面是我试图使用的代码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不是一个函数错误,我真的不明白为什么

这段代码基于这个例子,所以我想它应该可以工作


我做错了什么?

根据angular 5 changelog:

编译器选项enableLegacyTemplate现在默认为禁用 该元素自v4以来已被弃用。使用 相反

因此,您应该使用ng模板而不是模板:

ViewContainerRef 或将enableLegacyTemplate设置为true:

platformBrowserDynamic.bootstrapModuleAppModule,{enableLegacyTemplate:true} 但你应该知道


选项enableLegacyTemplate和元素都将在Angular v6中删除。

当您在*ngIf,else子句中引用时,它不能是任何任意组件,但必须是ng模板

例如

在具有类似于以下内容的源代码的组件中:

<div *ngIf="myCondition ; else elseSection">
    <!-- ... -->
</div>
<div #elseSection>
    <!-- ... -->
</div>
生成的源代码应如下所示:

<div *ngIf="myCondition ; else elseSection">
    <!-- ... -->
</div>
<ng-template #elseSection>
    <!-- ... -->
</ng-template>

ref:

在我的例子中,错误是因为我忘记了ngTemplateOutlet之前的*星号。对我来说,问题是组件中的变量和HTML文件中的模板使用了相同的名称。

似乎很明显,但我忽略了这一点

在较新版本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]出现两次并导致错误。

关于this.viewContainerRef.createEmbeddedViewthis.tpl@GünterZöchbauer-两个电话都会产生相同的错误我很高兴它在这里,否则我会错过它,它立刻帮助了我!我也错过了这个。。。谢谢马克西姆@谢申克斯,恕我直言。同一错误可能有多个原因。Maxim所引用的是OP报告的错误的多个原因之一。你能帮助澄清这个问题吗,我的问题似乎相关,