【问题标题】:How to fix Cannot read property 'time' of undefined in Angular Material?如何修复无法读取角度材料中未定义的属性“时间”?
【发布时间】:2019-05-09 12:08:32
【问题描述】:

我想显示从 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),即使我删除了一些数据,它也能正常工作。想知道为什么我的不是。

【问题讨论】:

  • 抱歉,您的代码有什么问题?你想在你的数据表上显示/做什么

标签: angular angular-material angular-material-7


【解决方案1】:

检查 WORKING 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" }
    }
  ];
}

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2019-05-21
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2020-03-03
    • 2019-05-24
    • 2023-03-19
    相关资源
    最近更新 更多