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

标签 angular typescript angular-template

this.child02.nativeElement 未定义,我不明白为什么。我究竟做错了什么?谢谢你。这是我的 current stackblitz.

应用程序组件.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;
    }
  }
}

应用程序组件.html:

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

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

</div>

上下文: 我正在尝试制作一个 snap-to-component-directive,类似于 this functionality (open in firefox).这是我的 current stackblitz. 我的问题是你将如何构建它?尽量不使用单例。

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

用于在 child 1 和 child 2 之间进行捕捉的上述逻辑的伪代码(有关上下文,请参阅 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);
}

感谢您的见解!

最佳答案

将@ViewChild 声明更新为:

@ViewChild('child02',{read: ElementRef}) child02: ElementRef;

保持其他一切不变。

Example

关于angular - 我的模板引用变量 .nativeElement 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51193187/

相关文章:

node.js - TypeScript 模块命名空间,同时在编译后保留多个文件

angular7 - 角 : how do I access the reference variable which is in a ng-template

Angular 渲染的 DOM html 自定义属性

javascript - 如果触发点击事件,Angular 会禁用标签一段时间?

Angular2 - HTTP RequestOptions header

typescript - 在 TypeScript 中拥有自己的@types-style 声明

javascript - angular.js 指令 templateUrl 无法绑定(bind)范围

html - 如何创建带有 Angular 数组的表行?

javascript - 无法使用 Angular 从 Assets 文件夹中检索 json 数据

javascript - 如何在浏览器(非移动设备)ionic中显示本地pdf文件