angular5 - 角度材料选项选择问题
问题描述
我正在尝试将 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 字段。
我得到的错误如下所示:
实际上,我正在尝试以示例演示的分类格式显示选择数据。
解决方案
发生错误Cannot read property 'org' of undefined
是因为该变量list
可能未在您的组件中定义。为了使模板能够使用变量呈现数据,组件必须公开该变量。
此外,由于您的 JSON 数据的结构,我认为不需要两个's,因为每个顶级对象*ngFor
只有一个属性。name
这在您的实际用例中可能会有所不同。此外,考虑为您的 JSON 数据使用接口,因为这将使您的 JSON 管理更简单。
推荐阅读
- rest - REST API 和 Delphi 错误:未提供所需的 OAuth 凭据
- c# - 找不到类型或命名空间名称“Dbset<>”(您是否缺少 using 指令或程序集引用?)
- python - Tkinter 查询 SQLite 数据库
- oracle-apex - 仅输出最后一个值
- python - Ansibe 是否支持 Python 3?如果您需要 Python 3 支持,请改用 `dnf` Ansible 模块
- docker - 在本地运行 Kubernetes 并连接到远程 Docker 服务器
- android - 你可以在 Android Studio 中构建一个反编译的 apk 吗?
- python - 过滤 Django 中的唯一数据
- java - Jetty / Grails 为隐藏资源返回 404 而不是 403
- java - 为什么 javac 在方法的返回类型上使用有界类型泛型编译此代码?它是无效的类型推断吗?