Home > Software engineering >  Using *ngIf on Date variable from nullable database column
Using *ngIf on Date variable from nullable database column

Time:09-27

I use a C# API which uses LinqToDB to return objects from an Oracle database, which is then mapped to a TypeScript interface and displayed in my application.

For example this C# class:

[Table(Name = "MY_TABLE")]
public class MyTable
{
    [Column(Name = "DATE_COLUMN")]
    public DateTime DateColumn { get; set; }
}

Which gets mapped to this interface:

export interface IMyTable {
    dateColumn: Date;
}

And that is then displayed in my component like this:

<p *ngIf="table.dateColumn">Date: {{table.dateColumn}}</p>

I expect this to not be displayed when the column in the database is null, instead I get text displayed like this: Date: 0001-01-01T00:00:00.

I have tried changing my interface declaration to dateColumn?: Date; but that had no effect.

I tried defining a minDate variable (minDate: Date = new Date(0);) and using that like this:

<p *ngIf="table.dateColumn != minDate">Date: {{table.dateColumn}}</p>

That doesn't work either, as the minDate variable is output as Thu Jan 01 1970 01:00:00 GMT 0100 (Greenwich Mean Time).

I could request a change to the C# API so that the class is a DateTime? but I'm not sure if that will fix it so I want to see if there's anything else I'm doing wrong first.

How can I apply a simple *ngIf on a Date in Angular?

CodePudding user response:

Aside from the typescript interface having the type Date | undefined, the c# property also needs to be nullable since DateTime is not nullable by default (unlike for example string).

[Column(Name = "DATE_COLUMN")]
public DateTime? DateColumn { get; set; }  // ? for nullable

Otherwise the date will be initialized with a default value already (0001-01-01T00:00:00).

CodePudding user response:

Couple of things you can try:

  • Hydrate the date object you get from your API, often times I find myself having to rehydrate a JS Date because it is actually treated as a string when it returns from the API as so: new Date(table.dateColumn).

  • Create your own pipe to handle empty date objects

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
       name: 'minNullDatePipe'
    })
    export class MinNullDatePipe implements PipeTransform {
     transform(value: Date | string): boolean{
        if (!value) return false;
    
        const minDate = new Date(0);
        const hydratedDate = new Date(value);
    
        return hydratedDate <= minDate //I am going to assume that anything less than min is automatically just in a bad state
     }
    }
    

Then use the above pipe as so: *ngIf="(table.dateColumn | minNullDatePipe)". Make sure to include that pipe in your module's declarations

  • Related