首页 > 解决方案 > 角度材料选项选择问题

问题描述

我正在尝试将 json 数据绑定到选择 angular material 的选项。但它的问题是数据没有绑定,而且整个页面都被冻结了。我写了下面的代码。

<mat-form-field class="full-width">
                        <mat-select placeholder="Select region">
                                <mat-option>-- None --</mat-option>
                                <mat-optgroup *ngFor="let region of list.org" [label]="region.name">
                                    <mat-option *ngFor="let r of region" [value]="r.name">
                                        {{r.name}}
                                    </mat-option>
                                </mat-optgroup>
                        </mat-select>
                </mat-form-field>

下面是我试图将其绑定到选择字段的 json 数据。

[
   {
      "id":"8a80806c6657045f016657c4bb53024c",
      "org":{
         "id":"8a8080a565e5c6f90165e5e908630d86",
         "name":"Account 1"
      },
      "account":{
         "id":"8a8080126634467a016634a534613852",
         "org":{
            "id":"8a8080a565e5c6f90165e5e908630d86",
            "name":"Account 1"
         },
         "accountType":"AWS"
      },
      "name":"Name 1"
   },
   {
      "id":"8a80806c6657045f016657c4bb53024c",
      "org":{
         "id":"8a8080a565e5c6f90165e5e908630d86",
         "name":"Account 1"
      },
      "account":{
         "id":"8a8080126634467a016634a534613852",
         "org":{
            "id":"8a8080a565e5c6f90165e5e908630d86",
            "name":"Account 1"
         },
         "accountType":"AWS"
      },
      "name":"Name 2"
   },
   {
      "id":"8a80806c6657045f016657c4bb53024c",
      "org":{
         "id":"8a8080a565e5c6f90165e5e908630d86",
         "name":"Account 2"
      },
      "account":{
         "id":"8a8080126634467a016634a534613852",
         "org":{
            "id":"8a8080a565e5c6f90165e5e908630d86",
            "name":"Account 2"
         },
         "accountType":"Azure"
      },
      "name":"Name 2"
   },
   {
      "id":"8a80806c6657045f016657c4bb53024c",
      "org":{
         "id":"8a8080a565e5c6f90165e5e908630d86",
         "name":"Account 3"
      },
      "account":{
         "id":"8a8080126634467a016634a534613852",
         "org":{
            "id":"8a8080a565e5c6f90165e5e908630d86",
            "name":"Account 3"
         },
         "accountType":"Cloud"
      },
      "name":"Name 3"
   }
]

实际上,我正在尝试实现以下 stackblitz 示例所演示的相同功能。但问题是我无法从 json 获取数据并绑定到 mat-select。任何人都可以帮助我解决这个问题。

实际上,我正在尝试将名称和 org.name绑定到 mat-select 字段。

我得到的错误如下所示:

在此处输入图像描述

实际上,我正在尝试以示例演示的分类格式显示选择数据。

堆栈闪电战的例子

标签: angular5angular-material2

解决方案


发生错误Cannot read property 'org' of undefined是因为该变量list可能未在您的组件中定义。为了使模板能够使用变量呈现数据,组件必须公开该变量。

此外,由于您的 JSON 数据的结构,我认为不需要两个's,因为每个顶级对象*ngFor只有一个属性。name这在您的实际用例中可能会有所不同。此外,考虑为您的 JSON 数据使用接口,因为这将使您的 JSON 管理更简单。

堆栈闪电战


推荐阅读