简体   繁体   中英

Angular *ngFor using PIPE not working when looping throw object

API data {
  id: 1,
  date: "21/may/2020",
  name: "Server A",
  geo: "Europa",
  status: "online"
}

 ngOnInit {
   this.col = [
     {field: 'name', header: 'Server Name'},
     {field: 'geo',  header: 'Geography'},
     {field: 'status', header: 'Status'},
     {field: 'date', header: 'Date'}
   ]
}

I'm testing angular PrimeNG and I have an data-table, where I set the values for each table row manually, it works fine.

template

 <ng-template>
  <td>
    <tr>
      <td>{{rowData.name}}</td>
      <td>{{rowData.geo}}</td>
      <td>{{rowData.status}}</td>
      <td>{{rowData.date | date: 'dd/MMM/yyyy'}}</td>
    </tr>
  <td>
  <ng-template>

I updated my template to dynamically loop through the object and set the data, how can I update my loop so I can insert the pipe when I render the "date" object.

 <td *ngFor="let col of column">
    {{rowData[col.field]}}
</td>

The above {{rowData[col.field]}} is working, but I not sure how to inside *ngFor="let col of columns " I can update only the col.date and add pipe into it.

This is what I trying but not successful, the baove is working but not the Pipe and also if I add keyvalue the tables data is not being displayed anymore.

<td *ngFor="let col of columns | keyvalue">
  <ng-container *ngIf="rowData[col.field] !== 'date'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'date'"> {{rowData[col.field] | date: 'dd/MMM/yyyy'}}</ng-container>
</td>

Any suggestion or example I can look into?

If i understand your question right, you want to apply pipe on the birthdate field, so you can do,

 <td *ngFor="let data of object">
    {{data["birthdate"] | date: 'dd/MMM/yyyy' }}
</td>

Use key value pipe like

<td *ngFor="let data of object | keyvalue">
  <ng-container *ngIf="data.key !== 'birthdate'"> {{data.value}}</ng-container>
   <ng-container *ngIf="data.key === 'birthdate'"> {{data.value | date: 'dd/MMM/yyyy'}}</ng-container>
</td>

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