简体   繁体   中英

ViewChild returns result, than becomes undefined (Angular 11)

My ViewChild gets properly logged on NgAfterViewInit but returns undefined after that. When it get's initialized it logs properly, but then (in my case function on resize) logs undefined.

HTML:

<div class="hor-nav" #horNav>
<ul [hidden]="!navModule" class="top-nav-module">
  <li *ngFor="let menu of menus; let i = index" class="hor-nav-item" #navItem>
    <a>
      ...Some link
    </a>
  </li>
</ul>

JS:

@ViewChild('horNav', {static: false}) horNav: ElementRef; // tried with static: true too


 ngAfterViewInit() {
    console.log('HOR NAV', this.horNav)   // This works just fine: HOR NAV ElementRef {nativeElement: div.hor-nav}
}



ngOnInit() {
   window.addEventListener('resize',  this.calculateNavBarWidth);
}

public calculateNavBarWidth() {
  console.log('Offset Width: ', this.horNav) // This returns undefined
}

Ok, figured it out. it was the event Listener. This works now:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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