简体   繁体   中英

How to format date fields in angular material table

I get this data from my web API

在此处输入图像描述

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 class="container mat-elevation-z8">
 <mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <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

在此处输入图像描述

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

Any idea, please?

Thanks

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

The problem was here

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

I had 'fechapresentacion' and that is not matched with

在此处输入图像描述

Now I see all right

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM