我的模板引用变量 .nativeElement 未定义

imn*_*ghn 5 typescript angular-template angular

this.child02.nativeElement 未定义,我不知道为什么。我究竟做错了什么?谢谢你。这是我目前的堆栈闪电战。

app.component.ts:

import { Component,ElementRef,ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

switchDirection = true;
head: ElementRef;

@ViewChild('child02') child02: ElementRef;

  onScroll(event: Event) {
    console.log("viewBoundaryL:" + (event.target as HTMLElement).scrollLeft);
    if((event.target as HTMLElement).scrollLeft >= 50 && this.switchDirection === true){
  console.log("nativeElement:" + this.child02.nativeElement)
  console.log(this.child02)
  console.log('snap')
this.child02.nativeElement.scrollIntoView({ behavior: 'smooth' });
  this.switchDirection = false;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

app.component.html:

Keep an eye on the console while scrolling...
<div class="container"  (scroll)="onScroll($event)" >

<child1></child1>
<child2 #child02></child2>
<child3></child3>

</div>
Run Code Online (Sandbox Code Playgroud)

上下文:我正在尝试创建一个 snap-to-component-directive,类似于此功能(在 firefox 中打开)。这是我目前的堆栈闪电战。 我的问题是你将如何构建它?尽量不使用单例。

有很多方法可以做到这一点,但这里有一个:当用户从一个组件水平滚动到另一个组件时,它进入视图中超过子组件边界 50 像素或更多,该组件将 scrollIntoView()。需要一个 switchDirection 变量,以便一旦发生捕捉,它就不会在相同的定位逻辑上运行。我想再次将其放入指令中。

用于在 child 1 和 child2 之间进行捕捉的上述逻辑的伪代码(有关上下文,请参见 stackblitz 控制台):

//snap from child1 to child2
    If (viewBoundary >= child1L + 50px && switchDirection === true){
child2.scrollIntoView();
switchDirection = false;
debounceTime(250);
}
//snap from child2 to child1
else if(viewBoundary <= child1R - 50px && switchDirection === false){
child1.scrollIntoView();
switchDirection = true;
debounceTime(250);
}
Run Code Online (Sandbox Code Playgroud)

感谢您的见解!

Sha*_*anu 5

将@ViewChild 声明更新为:

@ViewChild('child02',{read: ElementRef}) child02: ElementRef;
Run Code Online (Sandbox Code Playgroud)

保持其他一切不变。

例子


Ank*_*rma 2

您需要使用el如下方式访问该元素。这是因为您#child02在自定义组件上定义的不是本机元素,因此您需要通过el.

this.child02.el.nativeElement.scrollIntoView({ behavior: 'smooth' });
Run Code Online (Sandbox Code Playgroud)

我已验证,不再有控制台错误。

https://stackblitz.com/edit/angular-horizo​​ntalscrollsetup-logging2-e7b9jy?file=app/app.component.ts


但是,请将该属性用作#最后的手段,因为它会导致应用程序中的紧密耦合。

您可以参考以下链接了解更多信息。

https://angular.io/api/core/ElementRef