Html Angular 6:如何在ngFor中使用模板语法中的数组?

Html Angular 6:如何在ngFor中使用模板语法中的数组?,html,arrays,angular,ngfor,Html,Arrays,Angular,Ngfor,我有两个数组:books和booksDisplay。在我的模板中,我使用*ngFor迭代我的booksDisplay数组: <div *ngFor="let bookDisplay of booksDisplay"> <div class="book"> <div class="title" *ngIf="???">{{ ???.title }} </div> </div> {{???.title} 但是在

我有两个数组:booksbooksDisplay。在我的模板中,我使用
*ngFor
迭代我的
booksDisplay
数组:

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

{{???.title}

但是在我的
*ngFor
-元素中,我需要在我的
书籍
-数组中查找,其中
id
等于我的
书籍显示
-数组中当前的
bookId
。那么如何在我的
*ngFor
-元素中使用where子句之类的东西呢?

假设您的component.ts看起来像这样:

export class AppComponent {
   booksDisplay = [
    {
      id: 1,
      title: 'a'
    },
    {
      id: 2,
      title: 'b'
    },
    {
      id: 3,
      title: 'c'
    },
  ]
}
您可以将计数器设置为ngFor,并使用该值使用ngIf条件进行筛选,如下所示:

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

{{book.title}}
{{i}

像这样


{{book.description}}


像这样的东西应该可以用。但是,我最好在模型中准备数据,而不是在模板中进行此类计算

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

您可以在组件中创建一个dictionary/lookup属性,其中键是book id,并在
*ngFor
块中引用它。或者,您可以将两个数组合并到一个数组中并对其进行迭代。在我看来,您应该使用component.ts中的方法来过滤这些书籍,然后在UI中查找这些书籍。让UI做简单的渲染会提高你的性能。请你在添加数组结构中做个例子。谢谢。但它对我不起作用,因为索引不是图书id。一本书在booksDisplay数组中有多个元素。。。。还有别的办法吗?我觉得我误解了你的问题。你能提供一个小样本的数据,你正试图筛选?我可以相应地编辑我的答案。
<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>
checkIfExist(id: number) {
  return this.books.find( book => book['id'] === id ) 
}