angular 5:templateRef.createEmbeddedView不是函数

k10*_*102 22 angular2-template angular

这是我正在努力工作的代码(角度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);
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是我有这个(templateRef.createEmbeddedView is not a function)错误而且不太明白为什么.

此代码基于此示例https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682,所以我想它应该可行.

我究竟做错了什么?

yur*_*zui 53

根据angular 5 changelog:

现在,默认情况下禁用编译器选项enableLegacyTemplate,因为该元素自v4以来已弃用.请<ng-template> 改用.

所以你应该使用ng-template而不是template:

<ng-template #tpl>
   <h1>ViewContainerRef</h1>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

Stackblitz示例

或设置enableLegacyTemplatetrue:

platformBrowserDynamic().bootstrapModule(AppModule, { enableLegacyTemplate: true })
Run Code Online (Sandbox Code Playgroud)

Stackblitz示例

但你应该知道

选项enableLegacyTemplate和<template>元素都将在Angular v6中删除.


Max*_*bov 23

在我的情况下,错误是由于我忘记*(星号)之前 ngTemplateOutlet

  • 我很高兴它在这里,否则我会想念它,它立刻帮助了我! (5认同)
  • 这应该是一个评论,而不是一个答案,因为它没有回答这个问题 (2认同)
  • 我也错过了这个……谢谢马克西姆! (2认同)
  • @SheshankS。我不同意。同一错误可能有多个原因。Maxim引用** IS **的原因是OP报告了错误的多种原因之一。 (2认同)

Mon*_*i J 9

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

例如,

在您拥有类似于此的源代码的组件中:

<div *ngIf="myCondition ; else elseSection">
    <!-- ... -->
</div>
<div #elseSection>
    <!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)

生成的源代码应如下所示:

<div *ngIf="myCondition ; else elseSection">
    <!-- ... -->
</div>
<ng-template #elseSection>
    <!-- ... -->
</ng-template>
Run Code Online (Sandbox Code Playgroud)

参考:https://techoverflow.net/2018/02/17/how-to-fix-angular-typeerror-templateref-createembeddedview-is-not-a-function/