简体   繁体   English

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

[英]ViewChild does undefined during resize event

Let's see:让我们来看看:

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 is volatile here. this.sidebar在这里是不稳定的。 It logs out correctly during the lifecycle hooks, but when you resize the window it becomes null.它在生命周期挂钩期间正确注销,但是当您调整窗口大小时,它变为空。 No camelCase problem , no conditional dom , so what's wrong with the code?没有camelCase 问题,没有条件 dom ,那么代码有什么问题?

The problem is caused by how you register the event handlers.问题是由您注册事件处理程序的方式引起的。

With

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

this inside resetSidebar doesn't point to the AppSidebar class anymore. this里面的resetSidebar不再指向AppSidebar类。

Use .bind(this) to ensure this keeps working使用.bind(this)来确保this继续工作

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

You can also use arrow functions https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions您还可以使用箭头函数https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM