角度 5:templateRef.createEmbeddedView 不是函数 [英] angular 5: templateRef.createEmbeddedView is not a function

查看:20
本文介绍了角度 5:templateRef.createEmbeddedView 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要开始工作的代码(角度 5):

Here's the code I'm trying to get to work (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);
  }
}

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

The problem is that I've got this (templateRef.createEmbeddedView is not a function) error and don't really understand why.

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

This code is based on this example https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682 so I guess it should work.

我做错了什么?

推荐答案

根据 angular 5 更新日志:

According to angular 5 changelog:

编译器选项 enableLegacyTemplate 现在默认禁用,因为该元素自 v4 起已弃用.使用 相反.

The compiler option enableLegacyTemplate is now disabled by default as the element was deprecated since v4. Use <ng-template> instead.

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

So you should use ng-template instead of template:

<ng-template #tpl>
   <h1>ViewContainerRef</h1>
</ng-template>

Stackblitz 示例

或将 enableLegacyTemplate 设置为 true:

platformBrowserDynamic().bootstrapModule(AppModule, { enableLegacyTemplate: true })

Stackblitz 示例

但你应该知道

选项 enableLegacyTemplate 和