我正在尝试在角度6中测试scrollIntoView()并收到此错误-> TypeError: Cannot read property 'scrollIntoView' of null
规格:
beforeEach(() => {
fixture = TestBed.createComponent(BusinessInfoComponent);
component = fixture.componentInstance;
component.ngOnInit();
spyOn(document.getElementById('info-banner'), 'scrollIntoView').and.callThrough();
expect(document.getElementById('info-banner').scrollIntoView).toHaveBeenCalled();
expect(document.getElementById('info-banner')).not.toBeDefined();
fixture.detectChanges();
});
ts:
ngOnInit() {
document.getElementById('info-banner').scrollIntoView();
}
答案 0 :(得分:0)
尝试:
规格:
beforeEach(() => {
fixture = TestBed.createComponent(BusinessInfoComponent);
component = fixture.componentInstance;
component.ngOnInit();
spyOn(window.document.getElementById('info-banner'), 'scrollIntoView').and.callThrough();
expect(window.document.getElementById('info-banner').scrollIntoView).toHaveBeenCalled();
expect(window.document.getElementById('info-banner')).not.toBeDefined();
fixture.detectChanges();
});
角类
ngOnInit() {
window.document.getElementById('info-banner').scrollIntoView();
}
答案 1 :(得分:0)
document.getElementById('info-banner').scrollIntoView();
应该进入ngAfterViewInit()
生命周期挂钩。
基本上,任何DOM引用都应加入该钩子。执行ngOnInit()
时,DOM还不存在,因此会出错。
答案 2 :(得分:0)
尝试使用它。
n_components
// Get the reference of the variable
@ViewChild("myDiv") divView: ElementRef;
this.divView.nativeElement.scrollIntoView();
查看此链接
https://www.techiediaries.com/angular-elementref/
要访问外部元素,请检查