Search code examples
angularangular-ng-if

*ngIf with Fixed Date


How do I compare a variable date with a fixed date in an *ngIf call.

In my .ts file, I have:

  public _dateFrom: Date;

Then, I've tried this and it produced a compiler error:

<div *ngIf="_dateFrom >= (new Date('12/1/2010'))">        
</div>

Also tried this with the same problem:

<div *ngIf="_dateFrom >= (new Date(2010,12,1))">        
</div>

Any help would be appreciated.


Solution

  • Angular template doesn't allow creating variables. You could try to create a function in the controller and return the comparison.

    Two more things to notice:

    1. Months are zero indexed in Javascript. So you might have actually meant (2010, 11, 1) for 1st December 2010.
    2. It is better to compare the value of getTime() method instead of directly comparing the date objects.

    Try the following

    Controller

    isOldThan(year: number, month: number, date: number) {
      return this._dateFrom.getTime() >= (new Date(year, month, date)).getTime();
    }
    

    Template

    <div *ngIf="isOldThan(2010, 11, 1)">        
    </div>