Angular 6: TypeError: Cannot read property 'scrollIntoView' of null

Angular 6: TypeError: Cannot read property 'scrollIntoView' of null

我正在尝试在 angular 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();

}

尝试:

规格:

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();
  });

Angular class

ngOnInit() {
  window.document.getElementById('info-banner').scrollIntoView();
}

document.getElementById('info-banner').scrollIntoView(); 应该进入 ngAfterViewInit() 生命周期钩子。

基本上任何 DOM 引用都应该进入那个钩子。执行 ngOnInit() 时,DOM 尚不存在,因此出现错误。

试试这个。

  // Get the reference of the variable 
@ViewChild("myDiv") divView: ElementRef;

   this.divView.nativeElement.scrollIntoView();
<div id="info-banner" #myDiv >Info </div>

看看这个link

https://www.techiediaries.com/angular-elementref/

要访问外部元素,请检查此