繁体   English   中英

如何在HTML Angular 4中使用两个ngFor?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM