如何修复ChangeDetectorRef导入错误:ChangeDetectorRef没有提供程序

时间:2018-11-27 18:12:25

标签: javascript angular angular2-changedetection

将ChangeDetectorRef导入我的组件之一时遇到问题。

作为参考,族谱为PComponent(父级)-> Options-Grid(子级)-> FComponent(孙级)。

这是我在浏览器中遇到的错误:

StaticInjectorError(AppModule)[FComponent -> ChangeDetectorRef]: 
  StaticInjectorError(Platform: core)[FComponent -> ChangeDetectorRef]: 
    NullInjectorError: No provider for ChangeDetectorRef!

错误带我到的代码行在Grandparent组件(PComponent)中,在该行中实例化第一个子组件(Options-Grid)。

<div>
    <options-grid></options-grid>
</div>

我在构造函数中正确提供了ChangeDetectorRef并将其正确导入FComponent中。代码中的错误参考指向我实例化Options-Grid组件的PComponent html。

这是因为我没有在父组件中提供ChangeDetectorRef吗?

2 个答案:

答案 0 :(得分:1)

这样子组件将忽略父组件提供者

   constructor(@Optional() private ref: ChangeDetectorRef) {
        this.ref = ref;
    }

答案 1 :(得分:0)

所以我发现问题的原因是我试图在孙子组件中使用ChangeDetectorRef,这是不行的。

我改为在根父组件(PComponent)中使用ChangeDetectorRef,还为该组件实现了ngAfterContentChecked()方法。

这就是它在PComponent中的外观:

import { Component, OnInit, ViewContainerRef, ChangeDetectorRef, AfterContentChecked } from '@angular/core';

export class PComponent implements OnInit, AfterContentChecked {

    constructor(private cdr: ChangeDetectorRef){}

    ngAfterContentChecked() {
        this.cdr.detectChanges();
    }

    ngOnInit() {
        ....
    }
}