【问题标题】:How to populate dropdown from a json file?如何从 json 文件中填充下拉列表?
【发布时间】:2020-12-03 04:37:34
【问题描述】:

json 文件有...

{
"OrderTypeList": [
{
  "id": 1,
  "orderType": "XYZ"
},
...

}

组件代码:

  orderTypes: any[];

  getOrderTypes() { 
   this.OrderService.getJsonData('./assets/OrderTypes.json').subscribe((data:any[]) => {
        this.orderTypes = data;
  }); 
  }

下拉组件一行显示整个json对象?!我只想要订单类型。

<select name="types" id="#" *ngFor="let ot of orderTypes | keyvalue">
    <option selected="selected" value="one">{{ot.value | json}}</option>
</select>

【问题讨论】:

  • 请至少说明要求是什么

标签: angular angular-ui-bootstrap


【解决方案1】:

您必须在&lt;option&gt; 标记上包含*ngFor,并使用字符串插值从对象中获取您想要的属性。在您的情况下,您不需要管道 json。您可以检查对象的属性是否为数组,如果是,您可以在第二个*ngFor 上迭代它orderTypes[ot.key])

一个例子:

HTML:

<!-- First example with pipe 'keyvalue' -->
<ng-container *ngFor="let ot of orderTypes | keyvalue">
  <ng-container *ngIf="ot.key === 'orders'">

    <select name="types" id="#">
      <option 
        selected="selected" 
        value="one"
        *ngFor="let order of orderTypes[ot.key]">
          {{ ot.key }} => {{ order.orderType }}
      </option>
    </select>

  </ng-container>
</ng-container>

<br /><br />

<!-- Second example with array -->
<select name="types" id="#">
  <option 
    selected="selected" 
    value="one"
    *ngFor="let order of orderTypes.orders">
      {{ order.orderType }}
  </option>
</select>

TS:

orderTypes = {
  id: 1,
  orders: [  
    {
      id: 1,
      orderType: "XYZ"
    },
    {
      id: 2,
      orderType: "ABC"
    },
    {
      id: 3,
      orderType: "ZXC"
    }
  ]
};

以下是两者的堆栈闪电战: https://stackblitz.com/edit/angular-ivy-3pgerp?file=src/app/app.component.html

【讨论】:

  • 感谢您的回复。我刚试过。它显示空的下拉菜单。我还在控制台中看到以下错误。 “找不到类型为 'object' 的不同支持对象 '[object Object]'。NgFor 仅支持绑定到 Iterables,例如数组。”
  • 确保您传递给 *ngFor 的变量是一个数组。这是一个使用相同代码的 stackblitz 示例:stackblitz.com/edit/angular-ivy-3pgerp?file=src/app/…
  • 我理解那部分。这就是我尝试在 html 中使用 keyvalue 来避免该错误的原因。我的组件代码有什么问题?我应该做些什么来转换为数组吗?非常感谢。
  • 对不起,现在我明白了,我猜。我在 stackblitz 上编辑了代码和答案。希望对你有帮助
  • 谢谢。为什么这需要复杂?此外,它在一行中打印所有值,我想在我的下拉列表中有 3 个值。
猜你喜欢
  • 2021-04-04
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多