如何从 json 文件填充下拉列表?

How to populate dropdown from a json file?

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>

您必须在 <option> 标签中包含 *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