Sebastian S
Sebastian S

Reputation: 397

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?

Upvotes: 3

Views: 9329

Answers (3)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

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

Upvotes: 2

İlker A.
İlker A.

Reputation: 11

Like this; https://angular.io/guide/displaying-data

<ng-container *ngFor="let book of booksDisplay; let i = index"> 
   <ng-container *ngIf="book.id === '1'">  
   <p> {{book.description}}</p>
</ng-container> 

Upvotes: 0

Callat
Callat

Reputation: 3044

Assuming your component.ts looks something like this:

export class AppComponent {
   booksDisplay = [
    {
      id: 1,
      title: 'a'
    },
    {
      id: 2,
      title: 'b'
    },
    {
      id: 3,
      title: 'c'
    },
  ]
}

You can a counter to ngFor and use that value to filter on with ngIf conditional like so:

<div *ngFor="let book of booksDisplay; let i= index">
  <div class="book">
    <div class="title" *ngIf="i === book.id">{{ book.title }}
    </div>
    <p>{{i}}</p>
  </div>

Upvotes: 0

Related Questions