How can I compare "2022-01-07 15:43:00" string variable with current datetime in *ngIf
of angular html?
Please help and guide.
CodePudding user response:
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() );
}
CodePudding user response:
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.