所以我试图基于我的Angular应用程序的滚动来做一些事件。
我遇到了一个问题,因为我试图在HTML的帮助下访问一个元素 @ViewChild .
@ViewChild
我可以访问里面的元素 ngAfterViewInit() 但我无法在它之外访问它。它总是显示undefined。
ngAfterViewInit()
这是我的组件类:
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() 它没有经过训练。
ngAfterViewnit()
onScroll()
为什么在viewinit之后,我的元素会消失并变得未定义?我没有用任何 ngIf 或任何去除该元素的东西。
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>
以下是控制台错误:
你可以理解 this 回调函数中的关键字使用 bind() 方法。尝试以下操作
this
bind()
ngAfterViewInit(){ window.addEventListener('scroll', this.onScroll.bind(this), true); console.log(this.navBar.nativeElement); }
在没有约束力的情况下 这 关键字在 onScroll() 回调不指向类的作用域。
这