Home > Enterprise >  Instant update of the date variable for ngIf - Angular 2
Instant update of the date variable for ngIf - Angular 2

Time:09-30

There is a dropdown menu on my order card. There is a cancel button in this menu. The user can cancel the order within the first 10 minutes after creating it. I am using Moment.js package to compare dates.

order-card.component.ts

canBeCanceled = false;

ngOnInit() {
    this.canBeCanceled = moment().diff(order.createdAt, 'minutes', true) > 10;
}

order-card.compenent.html

<button *ngIf="canBeCanceled">Cancel</button>

When the page is first opened, everything will work fine, but if the user stays active on the page for more than 10 minutes, the button will not be hidden. I'm looking for a solution where I can change the variable instantly and hide the button instantly. Maybe with RxJS etc.

CodePudding user response:

You can simply use setTimeout method to achieve this.

// initially button is visible
canBeCanceled = true;

ngOnInit() {
    // 10000 is milliseconds which is 10 seconds
    setTimeout(()=>{
       // this line will be run after 10 seconds
       this.canBeCanceled = false;
    }, 10000)
}

CodePudding user response:

You could make canBeCanceled an observable that emits true initially, then emits false after 10 minutes. Of course if the "latest cancel time" is in the past, we only want to emit false:

this.canBeCanceled$ = moment().diff(latestCancelTime) < 0
  ? concat(of(true), of(false).pipe(delay(latestCancelTime)))
  : of(false);
<button *ngIf="canBeCanceled$ | async">Cancel</button>

Here's a little StackBlitz example.

  • Related