简体   繁体   中英

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?

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

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>

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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