Home > Blockchain >  How to format date fields in angular material table
How to format date fields in angular material table

Time:02-01

I get this data from my web API

enter image description here

The data is an array of IOferta

export interface IOferta {
 id: string
 idPresentada: string;
 descripcion: string;
 fechaPresentacion: Date;
 responsable: string;
 presentada: string;
 plazo: string;
 importe: number;
 organismo: string
}

I have this table un my component html

<section >
 <mat-table [dataSource]="dataSource" >
  <ng-container [matColumnDef]="column" *ngFor="let column of columnsToDisplay" [sticky]="true">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element; let i=index">
      <div *ngIf="column=='fechaPresentacion'">
        {{element[column] | date:'dd/MM/yyyy'}}
      </div>
      <div *ngIf="column=='importe'">
        {{element[column] | currency: 'EUR'}}
      </div>
      <div *ngIf="column!='fechaPresentacion' && column!='importe'">
        {{element[column]}}
      </div>
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky:true"></tr>

  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</mat-table>

But I see this

enter image description here

I don't understand why I don't see the fechePresentacion values

Any idea, please?

Thanks

CodePudding user response:

You not see the dates because they are "strings", not "date object".

I suggest you use map to transform the dates in your service

getData(){
  return this.httClient.get(....).pipe(
    map((res:any[])=>{
      res.forEach(x=>x.fechaPresentacion=new Date(x.fechaPresentacion))
      return res;
    })
  )
}

Idem when you get an unique proyect

getProject(id){
  return this.httClient.get(....).pipe(
    map((res:any)=>{
      res.fechaPresentacion=new Date(res.fechaPresentacion))
      return res;
    })
  )
}

So, your components receive the property "fechaPresentacion" as a Date object

NOTE: the conversion to Date object works because the string is in format yyyy-MM-ddThh:mm:ss

CodePudding user response:

The problem was here

this.columnsToDisplay = ['id', 'idPresentada', 'descripcion', 'fechaPresentacion', 'responsable', 'plazo', 'importe', 'organismo'];

I had 'fechapresentacion' and that is not matched with

enter image description here

Now I see all right

enter image description here

  • Related