Search code examples
angularviewchildelementref

Why cant @ViewChild run outside AfterViewInit?


so I am trying to do some events base on the scrolling of my Angular application.

I have a problem since I am trying to access a element in my HTML with the help of @ViewChild.

I can access the element inside ngAfterViewInit() but I can't access it outside of it. It always shows undefined.

Here is my component 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(){

  }
}

When i console log inside ngAfterViewInit() i get the HTML element but when i console log inside onScroll() it is undetfined.

Why does my element disappears and gets undefined after viewinit? I am not using any ngIf or anything that removes the element.

Here is the component HTML code.

  <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>

Here is the console error: enter image description here


Solution

  • You could bind the meaning of this keyword in the callback function using bind() method. Try the following

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

    Without binding, the scope of this keyword in the onScroll() callback doesn't point to scope of the class.