the*_*lin 7 javascript angular2-changedetection angular
我在将ChangeDetectorRef导入到我的组件之一时遇到问题。
作为参考,族谱树为PComponent(父级)-> Options-Grid(子级)-> FComponent(孙级)。
这是我在浏览器中遇到的错误:
StaticInjectorError(AppModule)[FComponent -> ChangeDetectorRef]:
StaticInjectorError(Platform: core)[FComponent -> ChangeDetectorRef]:
NullInjectorError: No provider for ChangeDetectorRef!
Run Code Online (Sandbox Code Playgroud)
该错误带我到的代码行是在Grandparent组件(PComponent)中,它在其中实例化了第一个子组件(Options-Grid)。
<div>
<options-grid></options-grid>
</div>
Run Code Online (Sandbox Code Playgroud)
我在构造函数中正确提供了ChangeDetectorRef并将其正确导入FComponent中。代码中的错误参考指向我实例化Options-Grid组件的PComponent html。
这是因为我没有在父组件中提供ChangeDetectorRef吗?
所以我发现问题的原因是我试图在孙组件中使用 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() {
....
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4484 次 |
| 最近记录: |