如何遍历数组数组?

时间:2018-05-15 04:28:07

标签: angular

我正在尝试从选择下拉列表中的json数组中显示数据。

<select class="form-control-custom" [(ngModel)]="selected"  placeholder="Filter Category By">
    <option>Get Countries By Currency Name</option>
    <option *ngFor="let currency of allData;">{{currency[0].name}}</option>          
</select>

我编写了一个逻辑,用于将所有货币数组放入我在select下拉列表中使用的allData字段中。 数据如下所示: enter image description here

所以我无法使用单个ngFor循环在另一个数组中迭代数组,我也只能在select下拉列表中显示数据。

以下是json数据的实际api: https://restcountries.eu/rest/v2/all

我试图在这个json数据中循环货币数组

非常感谢任何形式的帮助。

提前致谢。

2 个答案:

答案 0 :(得分:3)

您可以使用 <ng-container> 并嵌套 ngFor

 <select class="form-control-custom" [(ngModel)]="selected"  placeholder="Filter Category By">
    <option>Get Countries By Currency Name</option>
    <ng-container *ngFor="let currency of allData;">
      <option *ngFor="let currenObj of currency.currencies;"> {{currenObj.name}} </option>
    </ng-container>    
</select>

<强> DEMO STACKBLITZ

答案 1 :(得分:2)

以下是关于如何解决您所追求的问题的一些想法。 我喜欢这个为类似select的组件创建嵌套项的示例 https://codepen.io/sathomas/pen/VpJeEo

对于这个问题,这可能有点复杂。为了更简单,我相信你可以使用变量绑定来创建子选择选项。创建父 - >子关系。

<select [(ngModel)]="selectedCountry">
    <option *ngFor="country of AllData" [ngValue]='country'>{{country.name}}</option>
</select>
<select id='child' [(ngModel)]="selectedCurrency">
    <option *ngfor="currency of SelectedCountry.currencies" [ngValue]="currency.code'>{{currency.name}}</option>
</select>

你也可以使用county.currency作为第一个选择的ngValue,并在第二个选择中快捷地引用它。但是,对于完整的国家/地区,您可以在单独的选择元素中选择其他属性数组值。

注意:我编写了所有代码而没有测试语法,所以请原谅那里的任何错误。