版本:Angular 4。
我将父组件注入子组件以通过子组件访问父方法。
在父组件中,我不得不使用 ChangeDetectorRef,因为它有一个可以更新运行时的属性。
现在代码工作正常,但子组件规范为注入父组件的“ChangeDetectorRef”抛出错误。
错误:没有 ChangeDetectorRef 的提供者!
父组件
import { Component, AfterViewChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'parent-component',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent implements AfterViewChecked {
stageWidth: number;
constructor(private ref: ChangeDetectorRef) {
this.ref = ref;
}
//call this function as many times as number of child components within parent-component.
parentMethod(childInterface: ChildInterface) {
this.childInterfaces.push(childInterface);
}
ngAfterViewChecked() {
this.elementWidth = this.updateElementWidthRuntime();
this.ref.detectChanges();
}
}
子组件
import { Component, AfterViewInit } from '@angular/core';
import { ParentComponent } from '../carousel.component';
@Component({
selector: 'child-component',
templateUrl: './carousel-slide.component.html',
styleUrls: ['./carousel-slide.component.scss'],
})
export class ChildComponent implements AfterViewInit {
constructor(private parentComponent: ParentComponent) {
}
ngAfterViewInit() {
this.parentComponent.parentMethod(this);
}
}
应用程序.html
<parent-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
<child-component>
<div class="box">Content of any height and width</div>
</child-component>
</parent-component>
子组件的单元测试
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ParentComponent } from '../parent.component';
import { ChildComponent } from './child.component';
describe('ChildComponent', () => {
let component: ChildComponent;
let fixture: ComponentFixture<ChildComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ChildComponent],
providers: [ParentComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChildComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create \'ChildComponent\'', () => {
expect(component).toBeTruthy();
});
});
当我尝试在子规范的提供程序中添加 ChangeDetectorRef 时,出现以下错误。
失败:遇到未定义的提供者!通常这意味着你有一个循环依赖(可能是由使用'桶' index.ts 文件引起的。)
在谷歌搜索并尝试了很多事情之后,我无法找到解决方案。任何帮助表示赞赏。