Is there a way to determine the present date within a template?

In my component, I am working with an object that contains a timestamp.

What I aim to achieve is to dynamically check this timestamp in the template at runtime. For instance, I want to display the online status of a member by showing a green dot if they are currently online, and switching to a red dot if they go offline during runtime.

<div class="show_member_line">
  {{member.membername}} 
  <div *ngIf="member.lastactivity > ( !!!new Date().getTime()!!! - 120 )" class="status_online"></div>
  <div *ngIf="member.lastactivity < ( !!!new Date().getTime()!!! - 120 )" class="status_offline"></div>
</div>

Does anyone have any suggestions or ideas for how to approach this? :)

Answer №1

In my view, a more effective approach would involve creating a timer within your component as shown below:

import {Component, OnInit, OnDestroy} from '@angular/core';

private timerSubscription: any = null;
private lastActivityTime: Date;

ngOnInit(){
    let timer = Observable.timer(1000, 1000);
    this.timerSubscription = timer.subscribe((t:any) => {
        this.timerExecuted();
    });
}    

private timerExecuted(): void {
     var currentDate = new Date();
     currentDate.setHours(currentDate.getHours() - 2);  
     this.lastActivityTime = currentDate;
}

ngOnDestroy() {
    if (this.timerSubscription != null)
        this.timerSubscription.unsubscribe();
}

The 'lastActivityTime' will update every second and can be easily compared in your template like so:

<div class="show_member_line">
  {{member.membername}} 
  <div *ngIf="member.lastactivity > lastActivityTime" class="status_online"></div>
  <div *ngIf="member.lastactivity < lastActivityTime" class="status_offline"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to specialize generic methods in Typescript and make them more specific?

I am working with a generic static method in an abstract class: abstract class Base { static find<T extends Base>(options?: Object): Promise<T[]> { return findResults(options); } } Now, I am trying to specify its type in a derived cla ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

Automatically generate a component and seamlessly integrate it into your git repository

How can I automatically generate a component in Angular CLI (2^) and add it to Git without having to manually add each generated component using an IDE or CMD? ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

Angular import definitions corresponding to Font Awesome classes

https://fontawesome.com/icons/ When looking for an icon, the website provides a class to add to the HTML code. However, when using Angular, it is necessary to use icon definitions. For instance: <i class="fa-solid fa-star"></i> Wo ...

Struggling to access the properties of a Material-UI Button

import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | ...

What is preventing the dependency injection of AuthHttp (angular2-jwt) into a component?

UPDATE: Success! Problem Solved After much trial and error, I finally discovered the solution to my issue. It turned out that the problem lied in a simple configuration mistake. To rectify this, I made changes to both my package.json (dependencies section ...

``Engulfed in a sea of NgRx ViewModel

Apologies if this is unclear, there might be a fundamental aspect that I am overlooking, but here is my current issue: I am fetching a list of items from the backend, similar to: interface Item { id: number; userId: number; categoryId: number; } ...

Having trouble with ngx-slick-carousel? Need help with managing the next and prev buttons?

I'm facing an issue where the next and prev buttons are not visible on my carousel component, even though they seem to be working properly. When I inspect the elements, I can see that the buttons are there. How can I make them visible? Here is my cod ...

What steps can I take to resolve the keyboard problem with Ionic Capacitor?

Currently, I am working on a straightforward Ionic Capacitor application. My objective was to display or hide the keyboard based on certain scenarios. Despite referring to the capacitor documentation for assistance with the keyboard functionality, I encoun ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

Issue with parsing JSON data in AgGrid

I'm currently utilizing Ag-grid within my Angular project. The rowData is populated with data from a JSON file stored in the assets folder, which is fetched using HttpClient. However, I'm encountering an issue where the data fails to load and an ...

Utilizing Lodash in TypeScript to merge various arrays into one cohesive array while executing computations on each individual element

I am working with a Record<string, number[][]> and attempting to perform calculations on these values. Here is an example input: const input1 = { key1: [ [2002, 10], [2003, 50], ], }; const input2 = { key ...

The spinner failed to appear within 2000 milliseconds

After submitting the form, I want to display a spinner for 2000 milliseconds. However, my implementation using the setTimeout function is not working as expected. import { Component, OnInit } from '@angu ...

When attempting to access a URL directly, the Angular page not found feature fails to execute

Below is the defined route structure: const routes: Routes = [ { path: '', component: Layout, children: [ { path: 'home', component: HomeComponent}, { path: 'Product', component: ProductComponent ...

What is a simple way to exclude a prop from a declaration in a React/TypeScript project in order to pass it as undefined

I'm trying to accomplish this task but encountering a typescript error indicating that the label is missing. Interestingly, when I explicitly set it as undefined, the error disappears, as shown in the image. Here's how my interface is structured ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

Developing a databound listview in Ionic: A step-by-step guide

In the world of programming, each platform has its own way of handling lists. For example, Android uses RecyclerView, WPF uses ListView, and in Ionic, we have ion-list. If you have a list of strings like this: Animals:string[] = ["Dog", "Cat", "Human", "C ...

No declaration file was found for the module named 'vue2-timepicker'

Overview I integrated the vue2-timepicker plugin into my Typescript/Nuxt.js application. However, I encountered an issue with importing vue2-timepicker. import timepicker from 'vue2-timepicker' Could not find a declaration file for module &apos ...

Angular 2 - Utilizing `return` in the `then` method for async operations

Currently, I am facing a scenario where it would be very useful if there was a way to retrieve the value obtained in the .then() function. Allow me to explain why and what exactly I need. For almost every API call, I need to include the API_KEY and DEVIC ...