16

我们正在使用

TestBed.overrideComponent(CoolComponent, {
    set: {
      template: '<div id="fake-component">i am the fake component</div>',
      selector: 'our-cool-component',
      inputs: [ 'model' ]
    }
  })

覆盖一个组件。

该组件有一个我们在 ngOnInit 方法中配置的 ViewChild

@Component({
  selector: 'our-cool-component',
  templateUrl: 'cool.component.html'
})
export class CoolComponent implements OnInit, OnDestroy {
  @Input() model: SomeModel
  @ViewChild(CoolChildComponent) coolChildComponent;

  ngOnInit() {
    this.coolChildComponent.doStuff();
  }
}

反过来CoolComponent又存在于一个Wrapper组件中。

当我们调用夹具fixture.detectChanges()Wrapper,它会尝试构造 CoolComponent,但是当它调用 doStuff() 时它会立即死亡,因为它CoolChildComponent是未定义的。

有没有办法获得CoolComponent它的存根CoolChildComponent?似乎我们无法将其删除,Wrapper因为它仅通过模板引用,而不是作为组件的属性。

4

1 回答 1

8
ngOnInit() {
  this.coolChildComponent.doStuff();
}

应该

ngAfterViewInit() {
  this.coolChildComponent.doStuff();
}

因为

在调用 ngAfterViewInit 回调之前设置视图子级。

于 2016-09-05T08:07:28.260 回答