【问题标题】:Get object data from openDialog in angular material从角度材料中的openDialog获取对象数据
【发布时间】:2021-06-08 20:12:28
【问题描述】:

嗨,我是 Angular 新手。

所以我有这个 json 对象:

{
    "id": "1",
    "name": "2019-A",
    "createdBy": "Adrian",
    "creationDate": "1552211000",
    "orders": [{"id": "1", "name":"2019-01"}, {"id": "2", "name":"2019-02"}]
}

这是一个表示项目的对象。所以我有一个项目列表,当我单击一个项目时,我会显示一个包含所选项目订单的列表。

所以我为列表中的每个订单都有一个按钮。我想在点击按钮时显示订单详情。

这是关于按钮点击的代码:

<mat-grid-tile>
        <mat-selection-list [multiple]="false">
            <mat-list-option *ngFor="let ord of selectedOrders">
                <span>
                    {{ ord.name }}
                    <button mat-raised-button color="primary" (click)="openDialog(ord)">Order Details</button>                    
                </span>                
            </mat-list-option>
        </mat-selection-list>
    </mat-grid-tile>

order.component.html:

<div>{{id}} - {{name}}</div>

projects.component.ts:

openDialog(ord: OrderModel) {
    //debugger;
    this.dialog.open(OrdersComponent, {
      data: {
        id: ord.id,
        name: ord.name,
      }
    });
  }

这是结果:

无法加载订单的 ID 和名称。我只能看到 - 符号。

【问题讨论】:

  • 你可以这样做&lt;div&gt;{{data.id}} - {{data.name}}&lt;/div&gt;

标签: html json angular typescript


【解决方案1】:

试试这个

&lt;div&gt;{{data.id}} - {{data.name}}&lt;/div&gt;

在您的示例中,您将数据作为对象注入,而不是单独的 id 和 name。

【讨论】:

  • 最好在答案中包含解释而不是代码。
  • @BrunoMonteiro 好点,我认为这是不言自明的......但我会更新它
  • 如果只有代码,Stack Overflow 会标记你的答案,这就是为什么 :) stackoverflow.com/help/deleted-answers
【解决方案2】:

您需要在OrdersComponent 上获取数据。

要访问OrdersComponent 中的数据,您必须使用 MAT_DIALOG_DATA 注入令牌:

orders.component.ts

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';

@Component({
  selector: 'app-orders-component',
  template: 'passed in {{ data.name }}', // <- note: template calls data
})
export class OrdersComponent {
  constructor(@Inject(MAT_DIALOG_DATA) public data: {name: string}) { }
}

资源:

https://material.angular.io/components/dialog/overview

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2021-03-14
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多