首页 > 解决方案 > 我需要在与 ngFor angular 5 相同的选择框中给出州和地区的详细信息

问题描述

这是我的 json 值,

{
"location": [{
        "state": "state1",
        "cities": [{
                "city1": "city1"
            },
            {
                "city2": "city2"
            }
        ]
    },
    {
        "state": "state2",
        "cities": [{
                "city1": "city1"
            },
            {
                "city2": "city2"
            },
            {
                "city3": "city"
            }
        ]
    }
]

}

选择框中的示例输出:

状态1 - 州名 - 父级

city1 - 城市名称 - 孩子

城市2


状态2 - 状态名称 - 父级

city1 - 城市名称 - 孩子

城市2

城市3

    <select>
      <option *ngFor="let locations of location">
        {{locations.state}}{{locations.cities.citiname}}
      </option>
   <select>

它不是多选。这就像在城市下按州分组。

提前致谢。

标签: javascriptangularangular5ngfor

解决方案


您可以使用元素optgroup的属性。select

<select>
  <optgroup *ngFor="let location of locations" [label]="location.state">
    <option *ngFor="let city of location.cities">{{Utils.keys(city)[0]}}</option>
  </optgroup>
</select>

打字稿

Utils = {
     keys : Object.keys
}

您不能直接使用,Object.keys因为Object它是该表达式的一部分window/global并且angular无法评估该表达式。


推荐阅读