为什么不能在 AfterViewInit 之外使用 @ViewChild 运行?

Why cant @ViewChild run outside AfterViewInit?

所以我正在尝试根据 Angular 应用程序的滚动来执行一些事件。

我有一个问题,因为我试图在 @ViewChild 的帮助下访问我的 HTML 中的一个元素。

我可以访问 ngAfterViewInit() 中的元素,但我无法访问它之外的元素。它总是显示未定义。

这是我的组件 class:

export class NavBarComponent implements OnInit {

  @ViewChild('navBar')
  navBar:ElementRef;

  constructor(private renderer: Renderer2) {
  }

  ngAfterViewInit(){
    window.addEventListener('scroll', this.onScroll, true);
    console.log(this.navBar.nativeElement);
  }

  ngOnInit(): void {

  }

  onScroll(){
    console.log("I am scrolling right now.")
    console.log(this.navBar.nativeElement)
  }

  onResize(){

  }

  onTabClick(){

  }
}

当我在 ngAfterViewInit() 中进行控制台登录时,我得到了 HTML 元素,但是当我在 onScroll() 中进行控制台登录时,它是未定义的。

为什么我的元素在 viewinit 之后消失并变得未定义?我没有使用任何 ngIf 或任何删除元素的东西。

这是组件 HTML 代码。

  <section class="et-hero-tabs" >
    <h1>STICKY SLIDER NAV</h1>
    <h3>Sliding content with sticky tab nav</h3>
    <div class="et-hero-tabs-container" #navBar>
      <a class="et-hero-tab" href="">ES6</a>
      <a class="et-hero-tab" href="">Flexbox</a>
      <a class="et-hero-tab" href="">React</a>
      <a class="et-hero-tab" href="">Angular</a>
      <a class="et-hero-tab" href="">Other</a>
      <span class="et-hero-tab-slider"></span>
    </div>
  </section>

这是控制台错误:

您可以使用bind()方法在回调函数中绑定this关键字的含义。尝试以下

ngAfterViewInit(){
  window.addEventListener('scroll', this.onScroll.bind(this), true);
  console.log(this.navBar.nativeElement);
}

如果没有绑定,onScroll() 回调中 this 关键字的范围不会指向 class.

的范围