Typescript 如何使用ngFor在动态数组中循环?

Typescript 如何使用ngFor在动态数组中循环?,typescript,angular2-template,angular-material2,Typescript,Angular2 Template,Angular Material2,我正在尝试将动态数组绑定到md选项。但这是一个错误 <md-select id="hospital0{{index}}" placeholder="Hospital" style="width:100%; " name="hospital"> <md-option *ngFor="let hospital of hospitalList{{index}}" [value]="hospital.i

我正在尝试将动态数组绑定到md选项。但这是一个错误

                    <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>

{{hospital.name}
我尝试了另一种方法。在这种情况下,我获取select元素,然后向其添加选项。但它并没有在md选项中添加选项。 这个我试过了

    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);
public异步GetHospitalForCity(cityId:any){
console.log(cityId);
设ddl=(document.getElementById(“hospital000”);
let option=document.createElement(“option”);
option.value=“1”;
option.text=“Hospital1”;
ddl.appendChild(选项);

}

ngFor
中的数组是异步的时,您可以使用内置的
async管道

范例

<md-option *ngFor="let hospital of hospitalList{{index}} | async" [value]="hospital.id">
    {{ hospital.name }}
</md-option>

{{hospital.name}

我使用以下方法解决了问题:

ngFor="let hospital of hospitalList[index]"

正如Elvynia在评论中所说。

虽然这篇文章很旧,但我添加了一个类似的问题,上面的解决方案都没有解决我的问题。 但最终我找到了一个解决方案,如下所示

我们可以在ts中使用一个函数,该函数返回索引上的数组,并将其绑定到模板中,如下所示:

HTML:

ts:


无法读取未定义(““placeholder=”Hospital“style=”width:100%;”name=“Hospital”>]*ngFor=“let hospitalList{{index}}”[value]=“Hospital.id”>{{{Hospital.name}”):ng:///AppModule/MrWeeklyPlanComponent的属性“toUpperCase”。html@97:37分析器错误:意外标记{,在ng:///AppModule/MrWeeklyPlanComponent中的[let hospitalList{{{index}}]的第29列应为标识符、关键字或字符串。html@97:37(“ame=”hospital“>我在第一种方法中遇到了这个错误。我认为您不应该使用类似于
hospitalList{{{index}}
,因为模板表达式(使用
{}
)将永远不会被解析。相反,您应该在组件中使用此属性:
hospitalList:Array
,然后您可以在模板中使用
*ngFor=“let hospitalList of hospitalList[index]”“
。我添加了一个示例,您必须使用我演示的异步管道才能使其工作。无法读取未定义的属性“toUpperCase”(“”placeholder=“Hospital”style=“width:100%;”name=“Hospital”>]*ngFor=“let hospitalList{{index}}异步”[value]=“Hospital.id”>{{{Hospital.name}它没有解析占位符括号{}
*ngFor="let hospital of getArray(i+1); let i=index"
getArray(i: number): any[] {
  if (i === 1) {
     return this.hospital1;
  }else {
     return this.hospital2;
  }
}