[英]How to use two ngFor in html Angular 4?
在我的angular 4項目中,響應服務器的請求,我得到了兩個不同的數組,並且在模板中我想同時使用它們。 控制器代碼為:
this.contractService.getOwnerContract()
.subscribe(
res => {
this.contracts = res.contracts;
this.users= res.users;
})
在html中,我想使用兩個ngFor來使用contract和users屬性:
<div class="col-md-12 property-list-box" *ngFor="let contct of contracts ; let usr of users">
<div>{{contct.id}}</div>
<div>{{usr.id}}</div>
</div>
但是我寫的這個html代碼不起作用。 最好的解決方案是什么? 感謝您的協助。
這兩個數組是否總是具有相同數量的元素? 如果是這樣,您可以遍歷其中之一,並跟蹤索引
<div class="col-md-12 property-list-box" *ngFor="let contract of contracts ; let i = index">
<div>{{contracts[i].id}}</div>
<div>{{users[i].id}}</div>
</div>
如果它們不總是具有相同數量的元素,則需要2 ngFor
指令
您需要合並兩個數組並存儲在變量中,然后在模板的ngFor中使用該變量。
或者,您也可以使用管道將兩個數組“合並”為一個數組,然后對其進行迭代,這是一個示例:
@Pipe({
name: 'concat'
})
export class ConcatPipe {
transform(arr1, arr2) {
var arr = [];
arr1.forEach((elt, i) => {
arr.push({ state: elt, name: arr2[i] });
});
}
}
並以這種方式使用它:
<div class="col-md-12 property-list-box"*ngFor="let contract of contracts | merge:users" >
{{contract.id}}
</div>
使用下一個數組的index
。
<div class="col-md-12 property-list-box" *ngFor="let contct of contracts; index as i">
<div>{{contct.id}}</div>
<div>{{users[i].id}}</div>
</div>
查看更多: https : //angular.io/api/common/NgForOf#local-variables
如果兩個數組的大小相等,則可以簡單地使用其中一個數組,並為另一個數組使用索引。 例如:
{{user.name}} {{contact [i] .your_another_array_key}}如果數組的大小不相等,則必須以其他方式進行操作,以便可以在單個列表(如自定義數組)中進行迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.