【问题标题】:No provider for TemplateRef! (NgIf ->TemplateRef)没有 TemplateRef 的提供者! (NgIf -> 模板参考)
【发布时间】:2016-06-26 05:13:05
【问题描述】:

如果答案是可接受的答案,我会尝试显示复选标记:

template: `<div ngIf="answer.accepted">&#10004;</div>`

但我收到此错误:

EXCEPTION: No provider for TemplateRef! (NgIf ->TemplateRef)

我做错了什么?

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    你错过了 NgIf 前面的*(就像我们一样,几十次):

    <div *ngIf="answer.accepted">&#10004;</div>
    

    没有*,Angular 会看到ngIf 指令被应用于div 元素,但是由于没有*&lt;template&gt; 标签,它无法定位模板,因此错误。


    如果您在使用 Angular v5 时遇到此错误:

    错误:StaticInjectorError[TemplateRef]:
    StaticInjectorError[TemplateRef]:
    NullInjectorError: 没有 TemplateRef 的提供者!

    您的一个或多个组件模板中可能包含&lt;template&gt;...&lt;/template&gt;。将标签更改/更新为&lt;ng-template&gt;...&lt;/ng-template&gt;

    【讨论】:

    • 如果您使用不带星号的 ngSwitchCase 也会发生同样的异常!
    • 我想对此表示赞成,但我发现我很久以前就已经这样做了。
    • 错误检查器不能注意到它以 ng 开头并在底部添加:“ng__ found,你的意思是 *ng__ 吗?” (也许他们认为牵着开发者的手太有帮助了。)
    【解决方案2】:

    所以,我可以帮助您了解您犯了什么错误(以及在哪里犯了错误),但在此之前,我们需要阅读文档:

    通过在 元素(或以 * 为前缀的指令)。模板参考 对于嵌入视图被注入到构造函数中 指令,使用 TemplateRef 令牌。

    您还可以使用查询来查找与 组件或指令。

    所以:

    • 使用[ngIf]="something"时必须使用&lt;ng-template&gt;访问模板引用(例如:使用&lt;template&gt;&lt;ng-template&gt;时);
    • 使用*ngIf,您可以在需要的地方使用它,因为*保证访问模板参考(例如:使用&lt;span&gt;&lt;div&gt; 时);

    如果您在代码中使用 &lt;span [ngIf]="message"&gt; {{message}}&lt;/span&gt; 之类的东西,您可能会遇到一些错误。

    【讨论】:

    • 太棒了。你解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2018-05-01
    • 2023-01-28
    • 2016-08-30
    • 2017-08-13
    • 2012-07-07
    • 2020-12-01
    相关资源
    最近更新 更多