Reputation: 285
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. 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:
<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. What is the best solution? Thanks for helping in advanced.
Upvotes: 2
Views: 8860
Reputation: 266
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}}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.
Upvotes: 0
Reputation: 222522
You need to merge both the arrays and store in a variable and use the variable in your ngFor on the template.
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>
Upvotes: 1
Reputation: 18992
use index
for next array.
<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
Upvotes: 0
Reputation: 1106
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
Upvotes: 6