Pranam Bhat
Pranam Bhat

Reputation: 65

How to calculate the total time spent on a text box in a web page in Angular?

I have a web page. Where I have 2 text boxes.

I want to calculate the overall time spent on each box while clicking submit button at the end of the page.

clickInside() {
    this.text = 'clicked inside';
      this.wasInside = true;
      this.activeTime.activeStartDate();
  }

@HostListener('document:click')
clickout() {
  if (!this.wasInside) {
     this.text = 'clicked outside';
   }
   this.wasInside = false;
     this.activeTime.activeEndDate();
   }

Upvotes: 0

Views: 704

Answers (1)

Federico Galfione
Federico Galfione

Reputation: 1109

I've created a little POC to manage your request. You could write a really simple directive to implement in each input where you want to track the time spent.

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[calcTime]'
})
export class CalcTimeDirective {
  private timeSpentMs: number = 0;
  private lastDate: Date;
  constructor() { }

  @HostListener('focus') onFocus(){
    this.lastDate = new Date();
  }

  @HostListener('blur') onBlur(){
    this.timeSpentMs += (new Date() as any) - (this.lastDate as any);
  }

  public reset(){
    this.timeSpentMs = 0;
  }

  public getTime(){
    return this.timeSpentMs;
  }

  public getTimeSeconds(){
    return this.timeSpentMs / 1000;
  }
}

You can find the code with a simple example here. Hope it can help you.

Upvotes: 2

Related Questions