角度材料选项选择出现问题

时间:2018-10-09 16:08:42

标签: angular5 angular-material2

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

<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字段。

我得到的错误如下:

enter image description here

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

Example of stackblitz

1 个答案:

答案 0 :(得分:0)

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

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

Stackblitz

相关问题