【发布时间】:2018-06-21 12:48:21
【问题描述】:
我正在尝试学习如何在我的 angular4 应用程序中使用模板引用,到目前为止,从我似乎理解的文档来看,我们可以使用模板引用中的视图,但是当我尝试实现相同时,我得到了跟随错误
错误错误:没有 TemplateRef 的提供者!
以下是我的代码示例
import { Component, OnInit, EventEmitter, ViewChild, TemplateRef, ElementRef } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private template: TemplateRef<any>, private element: ElementRef) { }
ngOnInit() {
this.template.createEmbeddedView(this.element);
}
}
<ng-template>
<div style='border: solid 2px yellow;
width: 100%;
height: 50px;
background-color: #adadad;'>
</div>
</ng-template>
<div style='border: solid 2px red;
width: 100%;
height: 180px;
background-color: #adadad;'>
</div>
这里我想要实现的是将存在的 html 放在 .
更新 1
我已经把我的代码改成了这个
@ViewChild('tmp1') template: TemplateRef<any>;
constructor(private element: ElementRef) { }
ngOnInit() {
this.template.createEmbeddedView(this.element.nativeElement);
}
<ng-template #tmp1>
<div style='border: solid 2px yellow;
width: 100%;
height: 50px;
background-color: #adadad;'>
</div>
</ng-template>
<div style='border: solid 2px red;
width: 100%;
height: 180px;
background-color: #adadad;'>
</div>
但我仍然无法在模板中插入元素
【问题讨论】:
-
将@ViewChild 用于
private template: TemplateRef<any>而不是构造函数注入
标签: javascript angular angular5 angular-template