john
john

Reputation: 17

Access @HostListener properties from inside constructor? Typescript

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)

  }

Upvotes: 1

Views: 93

Answers (1)

Ivan Tarskich
Ivan Tarskich

Reputation: 1527

Use the AfterViewInit() hook, then you can be sure the dom is available. During change detection, Angular automatically updates the data with the value.

Upvotes: 2

Related Questions