簡體   English   中英

如何修復無法讀取Angular Material中未定義的屬性'time'?

[英]How to fix Cannot read property 'time' of undefined in Angular Material?

我想顯示從api到Angular Material Datatable的可用數據。 響應並不總是返回相同的內容(見下文)。 我正在嘗試合並* ngIf。

{
  id: "123",
  date: "2019-04-15"
  am_in: { id: "0001", time: "08:00 AM" }
},
{
  id: "456",
  date: "2019-04-16"
  am_in: { id: "0031", time: "07:00 AM" },
  am_out: { id: "0041", time: "11:24 AM" }
}

我在網上看過樣品( https://stackblitz.com/edit/angular-w9ckf8?file=app%2Fapp.component.ts ),即使我刪除了一些數據,它也能正常工作。 想知道為什么我的不是。

檢查 工作STACKBLITZ

這是從您提供的鏈接和您正在使用的數據直接分叉的!


我在網上看過樣品( https://stackblitz.com/edit/angular-w9ckf8?file=app%2Fapp.component.ts ),即使我刪除了一些數據,它也能正常工作。 想知道為什么我的不是。

您的component.html可能如下所示:〜

<mat-toolbar color="primary">My full table</mat-toolbar>

<mat-table #table [dataSource]="yetAnotherdataSource" matSort *ngIf="yetAnotherdataSource.length > 0">

  <ng-container matColumnDef="ID">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element?.id}} </mat-cell>
    </ng-container>


    <ng-container matColumnDef="Date">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Date </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element?.date}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="AM IN">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Am_in </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element?.am_in?.time}} </mat-cell>
    </ng-container>

  <ng-container matColumnDef="AM OUT">
        <mat-header-cell *matHeaderCellDef mat-sort-header>Am_out </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element?.am_out?.time}} </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="row.toggle(row)">
    </mat-row>
</mat-table>

<div *ngIf="yetAnotherdataSource.length === 0">No data</div>

和你的component.ts有你提供的數據:〜

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  name = 'Angular 5';
  displayedColumns = ['ID', 'Date', 'AM IN', 'AM OUT'];
  yetAnotherdataSource = [
    {
      id: "123",
      date: "2019-04-15",
      am_in: { id: "0001", time: "08:00 AM" }
    },
    {
      id: "456",
      date: "2019-04-16",
      am_in: { id: "0031", time: "07:00 AM" },
      am_out: { id: "0041", time: "11:24 AM" }
    }
  ];
}

希望這有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM