Ngfor inside another Ngfor Angularx

Asked

Viewed 435 times

1

I am trying to run a loop to show the values, respectively for each user, but with ngIf nothing appears, as I put here in the example, and without ngIf are shown the two values for the two users, and each user has only one value.

users = [
  {'id': 15,'name':'João'},
  {'id': 16,'name':'Maria'}
];
listPrices = [
  {'id_price': 1,'id_user': 15,'price': 2.50},
  {'id_price': 3,'id_user': 16,'price': 1.50}
];
<div *ngFor="let user of users">
  <div *ngFor="let item of listPrices">
    <span *ngIf="item.id_user === data.id">
      {{item.price}}
    </span>
  </div>
</div>

  • 3

    In this case, it wouldn’t just be a syntax error, from data.id for user.id

  • 1

    Guy was easier to make a mapping in your typescript.

  • Why wouldn’t it be the syntax problem? I think that’s right. The ideal would be to map the controller and generate a single object to give only one ngFor, but this way the template works also.

1 answer

1

If your code is exactly as the one placed in the question, there is a small error in ngIf. You call data.id when it’s actually user.id the right thing to do.

users = [
  {'id': 15,'name':'João'},
  {'id': 16,'name':'Maria'}
];
listPrices = [
  {'id_price': 1,'id_user': 15,'price': 2.50},
  {'id_price': 3,'id_user': 16,'price': 1.50}
];
<div *ngFor="let user of users">
  <div *ngFor="let item of listPrices">
    <span *ngIf="item.id_user === user.id">
      {{item.price}}
    </span>
  </div>
</div>

You can also do a treatment in your controller on these objects and get one to use in the template. It would look something like this:

userTemplate = users.map(user => {
    user.prices = listPrices.filter(list => user.id === list.id_user)
    return user
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.