Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: How to use an array in template syntax with ngFor?

I have two arrays: books and booksDisplay. In my template I use *ngFor to iterate through my booksDisplay array:

<div *ngFor="let bookDisplay of booksDisplay">
   <div class="book">
      <div class="title" *ngIf="???">{{ ???.title }}
   </div>
</div>

But inside my *ngFor-Element I need to look up in my books-Array, where id is equal to the current bookId in my booksDisplay-Array. So how can I use something like a where clause inside my *ngFor-Element?

like image 567
Sebastian S Avatar asked Nov 21 '25 13:11

Sebastian S


1 Answers

Something like this should work. However, I would better prepare data in a model instead of making such calculations in the template..

<div *ngFor="let bookDisplay of booksDisplay>
   <div class="book">
      <ng-container *ngIf="checkIfExist(bookDisplay.id)">
        <div class="title">{{ books[bookDisplay.id] }}
      </ng-container>
   </div>
</div>

Template:

checkIfExist(id: number) {
  return this.books.find( book => book['id'] === id ) 
}
like image 159
Julius Dzidzevičius Avatar answered Nov 24 '25 04:11

Julius Dzidzevičius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!