【问题标题】:Error: No provider for TemplateRef! Angular4错误:没有 TemplateRef 的提供者!角4
【发布时间】: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&lt;any&gt; 而不是构造函数注入

标签: javascript angular angular5 angular-template


【解决方案1】:

由于您指定了 templateURL 和 styleURL,看起来您使用的是 Angular 5,而不是 Angular 4。在这种情况下,您希望将您的模板/html 放在您在模板中指定的模板文件中。即 app.component.html

【讨论】:

  • 即使在角度 2,4 中也是可能的。
  • 对于 AngularJS 4,属性是 @Componet 中的“模板”。上面的代码使用了templateUrl,这是AngularJS 5中的一个新特性
  • 嗨@Aravind,你能看看我的updaetd问题吗,我仍然无法实现它
  • 没有“AngularJS 4”或“AngularJS 5”之类的东西。 AngularJS 是 v1.x
猜你喜欢
  • 1970-01-01
  • 2018-02-28
  • 2018-08-08
  • 2018-04-03
  • 2018-03-16
  • 2018-03-04
  • 2019-08-12
  • 2016-06-26
  • 1970-01-01
相关资源
最近更新 更多