Ответ 1
ngOnInit() {
this.coolChildComponent.doStuff();
}
должен быть
ngAfterViewInit() {
this.coolChildComponent.doStuff();
}
Просмотр дочернего элемента устанавливается до вызова функции ngAfterViewInit.
Мы используем
TestBed.overrideComponent(CoolComponent, {
set: {
template: '<div id="fake-component">i am the fake component</div>',
selector: 'our-cool-component',
inputs: [ 'model' ]
}
})
для переопределения компонента.
У компонента есть ViewChild, который мы настраиваем в нашем методе ngOnInit
@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
- undefined.
Есть ли способ добраться до CoolComponent
, чтобы заглушить его CoolChildComponent
? Похоже, что мы можем получить его от Wrapper
, потому что он ссылается только через шаблон, а не как свойство компонента.
ngOnInit() {
this.coolChildComponent.doStuff();
}
должен быть
ngAfterViewInit() {
this.coolChildComponent.doStuff();
}
Просмотр дочернего элемента устанавливается до вызова функции ngAfterViewInit.