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)
或设置enableLegacyTemplate为true:
platformBrowserDynamic().bootstrapModule(AppModule, { enableLegacyTemplate: true })
Run Code Online (Sandbox Code Playgroud)
但你应该知道
选项enableLegacyTemplate和<template>元素都将在Angular v6中删除.
Max*_*bov 23
在我的情况下,错误是由于我忘记*(星号)之前 ngTemplateOutlet
当您在*ngIf中引用时,else子句不能是任意组件,但它必须是ng-template.
例如,
在您拥有类似于此的源代码的组件中:
Run Code Online (Sandbox Code Playgroud)<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>
参考:https://techoverflow.net/2018/02/17/how-to-fix-angular-typeerror-templateref-createembeddedview-is-not-a-function/
| 归档时间: |
|
| 查看次数: |
25106 次 |
| 最近记录: |