如何使用 ngFor 循环动态数组?
How to loop in dynamic array using ngFor ?
我正在尝试将动态数组绑定到 md-option。但它正在抛出错误。
<md-select id="hospital0{{index}}" placeholder="Hospital" style="width:100%; " name="hospital">
<md-option *ngFor="let hospital of hospitalList{{index}}" [value]="hospital.id">{{ hospital.name }}</md-option>
</md-select>
我尝试了另一种方法。因为我正在获取 select 元素,然后向其添加选项。但它没有在 md-option 中添加选项。
这个我试过了
public async GetHospitalForCity(cityId: any) {
console.log(cityId);
let ddl = (<HTMLSelectElement>document.getElementById("hospital000"));
let option = document.createElement("option");
option.value = "1";
option.text = "Hospital1";
ddl.appendChild(option);
}
当ngFor
里面的数组是异步的时候,你使用angular中内置的async pipe
。
例子
<md-option *ngFor="let hospital of hospitalList{{index}} | async" [value]="hospital.id">
{{ hospital.name }}
</md-option>
我使用以下方法解决了我的问题:
ngFor="let hospital of hospitalList[index]"
正如 Elvynia 在评论中所说。
虽然 post 是旧的,但我添加了一个类似的问题,上述解决方案中的 none 解决了我的问题。
但最终我找到了如下解决方案。
我们可以在 ts 中有一个函数 returns 索引上的数组并将其绑定到模板中,如下所示:
HTML:
*ngFor="let hospital of getArray(i+1); let i=index"
ts:
getArray(i: number): any[] {
if (i === 1) {
return this.hospital1;
}else {
return this.hospital2;
}
}
我正在尝试将动态数组绑定到 md-option。但它正在抛出错误。
<md-select id="hospital0{{index}}" placeholder="Hospital" style="width:100%; " name="hospital">
<md-option *ngFor="let hospital of hospitalList{{index}}" [value]="hospital.id">{{ hospital.name }}</md-option>
</md-select>
我尝试了另一种方法。因为我正在获取 select 元素,然后向其添加选项。但它没有在 md-option 中添加选项。 这个我试过了
public async GetHospitalForCity(cityId: any) {
console.log(cityId);
let ddl = (<HTMLSelectElement>document.getElementById("hospital000"));
let option = document.createElement("option");
option.value = "1";
option.text = "Hospital1";
ddl.appendChild(option);
}
当ngFor
里面的数组是异步的时候,你使用angular中内置的async pipe
。
例子
<md-option *ngFor="let hospital of hospitalList{{index}} | async" [value]="hospital.id">
{{ hospital.name }}
</md-option>
我使用以下方法解决了我的问题:
ngFor="let hospital of hospitalList[index]"
正如 Elvynia 在评论中所说。
虽然 post 是旧的,但我添加了一个类似的问题,上述解决方案中的 none 解决了我的问题。 但最终我找到了如下解决方案。
我们可以在 ts 中有一个函数 returns 索引上的数组并将其绑定到模板中,如下所示:
HTML:
*ngFor="let hospital of getArray(i+1); let i=index"
ts:
getArray(i: number): any[] {
if (i === 1) {
return this.hospital1;
}else {
return this.hospital2;
}
}