代码之家  ›  专栏  ›  技术社区  ›  Allamo Olsson

为什么@ViewChild不能在AfterViewUnit外运行?[副本]

  •  1
  • Allamo Olsson  · 技术社区  · 4 年前

    所以我试图基于我的Angular应用程序的滚动来做一些事件。

    我遇到了一个问题,因为我试图在HTML的帮助下访问一个元素 @ViewChild .

    我可以访问里面的元素 ngAfterViewInit() 但我无法在它之外访问它。它总是显示undefined。

    这是我的组件类:

    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(){
    
      }
    }
    

    当我登录控制台时 ngAfterViewnit() 我得到了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>
    

    以下是控制台错误: enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   Michael D    4 年前

    你可以理解 this 回调函数中的关键字使用 bind() 方法。尝试以下操作

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

    在没有约束力的情况下 关键字在 onScroll() 回调不指向类的作用域。