1

How can I compare "2022-01-07 15:43:00" string variable with current datetime in *ngIf of angular html?

Please help and guide.

Giannis
  • 1,790
  • 1
  • 11
  • 29
ganesh
  • 416
  • 1
  • 11
  • 32
  • There are a lot of things you can try. I think the simplest is to create a method in you component to do something like this: `return new Date() === new Date('2022-01-07 15:43:00')` . And then your `*ngIf` condition will be something like `*ngIf="yourMethod()"` – tufonas Dec 13 '21 at 13:12

2 Answers2

0

You can use a function in the ngIf directive, like *ngIf="showBasedOnDate(date)" create this function in your TS file and handle all logic there. Return either true or false to show the elements.

<div *ngIf="showBasedOnDate(date)"> 
   I am shown
</div>

showBasedOnDate(date) {
 // here you can have as much logic as you would like, based on your needs. 
 return (date === new Date() );
}

cloned
  • 6,346
  • 4
  • 26
  • 38
  • can I check less than in `showBasedOnDate` function? I have one string datetime which needs to check `is less than` with current datetime. – ganesh Dec 13 '21 at 13:42
  • You can do whatever logic you want in the function. – cloned Dec 13 '21 at 14:45
0

Question is: is that really what you want? The element will be visible for a ridicoulosly short amount of time only. I guess you want to show an element once a given time was reached.

Also remember that binding a method to the template is generally considered being not good practice because it is recalculated on any render cycle. It would be a better approach to bind to an async Observable that emits on a given time.

So your binding might look like

*ngIf="(isNow$ | async)===true"

and your concrete implementation might be something like

isNow$: Observable<boolean>;
...
const dateDifference = date-Date.now();
this.isNow$ = of(true).pipe(delay(dateDifference);

which will basically let you one calculate the moment and then will display the element inside the dom from then on. If you really want to only see the DOM-element at the very moment the times are equal and instantly turn it off again you should re-emit the Observable to false.

Malte
  • 114
  • 9