简体   繁体   English

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

[英]How to use two ngFor in html Angular 4?

In my angular 4 project in response of a request from server I get two different arrays and in template I want to use both of them. 在我的angular 4项目中,响应服务器的请求,我得到了两个不同的数组,并且在模板中我想同时使用它们。 the controller code is: 控制器代码为:

this.contractService.getOwnerContract()
  .subscribe(
    res => {
     this.contracts = res.contracts;
     this.users= res.users;
  })

and in html I want to use two ngFor to use contract and users properties: 在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>

but this html code that I wrote doesn't work. 但是我写的这个html代码不起作用。 What is the best solution? 最好的解决方案是什么? Thanks for helping in advanced. 感谢您的协助。

Do these two arrays always have the same number of elements? 这两个数组是否总是具有相同数量的元素? If so you can iterate over one of them, and keep track of index 如果是这样,您可以遍历其中之一,并跟踪索引

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

If they don't always have the same number of elements you'll need 2 ngFor directives 如果它们不总是具有相同数量的元素,则需要2 ngFor指令

You need to merge both the arrays and store in a variable and use the variable in your ngFor on the template. 您需要合并两个数组并存储在变量中,然后在模板的ngFor中使用该变量。

Or you could a pipe to "merge" your two arrays into a single array and then you can iterate over it Here is a sample: 或者,您也可以使用管道将两个数组“合并”为一个数组,然后对其进行迭代,这是一个示例:

@Pipe({
  name: 'concat'
})
export class ConcatPipe {
  transform(arr1, arr2) {
    var arr = [];
    arr1.forEach((elt, i) => {
      arr.push({ state: elt, name: arr2[i] });
    });
  }
}

And use it this way: 并以这种方式使用它:

<div class="col-md-12 property-list-box"*ngFor="let contract of contracts | merge:users"  >
  {{contract.id}} 
</div>

use index for next array. 使用下一个数组的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>

See more : https://angular.io/api/common/NgForOf#local-variables 查看更多: https : //angular.io/api/common/NgForOf#local-variables

If your both arrays have equal size then you can simple use any one of the Array and use the index for another. 如果两个数组的大小相等,则可以简单地使用其中一个数组,并为另一个数组使用索引。 For example: 例如:

{{user.name}} {{ contacts[i].your_another_array_key}} {{user.name}} {{contact [i] .your_another_array_key}}

If array is not equal in size then you have to manipulate in some other fashion so it can be iterable in a single list like custom array. 如果数组的大小不相等,则必须以其他方式进行操作,以便可以在单个列表(如自定义数组)中进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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