英文:
Access @HostListener properties from inside constructor? Typescript
问题
我试图记录并存储鼠标在页面上的最后移动时间。这有些困难。
我已经阅读了文档https://angular.io/api/core/HostListener,但我不明白为什么@HostListener属性不可用于Typescript文档的其余部分。
```typescript
import { Component, HostListener, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
isExpanded = false;
active: boolean = false;
counter: any = 10;
document: any = 0;
dateTimeNow: Date;
@HostListener('document:mousemove', ['$event'])
onMouseMove(e: any) {
console.log(e, this.dateTimeNow = new Date());
}
constructor(private router: Router) {
let intervalId = setInterval(() => {
this.counter = this.counter - 1;
console.log(this.counter);
var a = this.onMouseMove;
console.log(a);
if (this.counter === 3) {
this.counter = 10;
}
if (this.counter === 0) {
clearInterval(intervalId);
this.router.navigateByUrl('/');
}
}, 1000)
}
}
英文:
I'm trying to log and store the last time a mouse move occurred on the page. Proving Difficult.
I've read the docs https://angular.io/api/core/HostListener but I'm cannot understand why the @HostListener properties aren't available to the rest of the Typescript document.
import { Component, HostListener, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
isExpanded = false;
active: boolean = false;
counter: any = 10;
document: any = 0;
dateTimeNow: Date;
@HostListener('document:mousemove', ['$event'])
onMouseMove(e: any) {
console.log(e, this.dateTimeNow = new Date());
}
constructor(private router: Router) {
//this.dateTimeNow = new Date();
//rather than setting a new date I want the date from inside of the @HostListener
//then store this in another variable.
let intervalId = setInterval(() => {
this.counter = this.counter - 1;
console.log(this.counter);
var a = this.onMouseMove;
console.log(a);
if (this.counter === 3) {
this.counter = 10;
}
if (this.counter === 0) {
clearInterval(intervalId);
this.router.navigateByUrl('/');
}
}, 1000)
}
答案1
得分: 1
使用AfterViewInit()钩子,然后您可以确保DOM可用。在变更检测期间,Angular会自动更新数据的值。
英文:
Use the AfterViewInit() hook, then you can be sure the dom is available.
During change detection, Angular automatically updates the data with the value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论