ViewChild 在调整大小事件期间未定义

ViewChild does undefined during resize event

让我们看看:

import {
  Component, OnInit, ViewEncapsulation, Input, ElementRef, ViewChild, AfterViewInit
} from '@angular/core';

@Component({
  selector: 'app-sidebar',
  template: `
  <aside #sidebar>
  Sidebar
  </aside>`,
})
export class AppSidebar implements OnInit, AfterViewInit {
  @ViewChild('sidebar')
  private sidebar: ElementRef;

  constructor() {
  }

  ngOnInit() {
    console.log('OnInit has:', this.sidebar)
    window.addEventListener('resize', this.resetSidebar);
  }

  ngAfterViewInit() {
    console.log('AfterViewInit has:', this.sidebar);
  }

  resetSidebar() {
    console.log(this.sidebar);
  }
}

this.sidebar 在这里是不稳定的。它在生命周期挂钩期间正确注销,但是当您调整 window 的大小时它变为空。没有, no ,所以代码有什么问题?

问题是由您注册事件处理程序的方式引起的。

 window.addEventListener('resize', this.resetSidebar);

this inside resetSidebar 不再指向 AppSidebar class。

使用.bind(this)确保this继续工作

 window.addEventListener('resize', this.resetSidebar.bind(this);

你也可以使用箭头函数https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 window.addEventListener('resize', (event) => this.resetSidebar(event);