【问题标题】:Angular 6: How to use an array in template syntax with ngFor?Angular 6:如何在模板语法中使用 ngFor 中的数组?
【发布时间】:2018-07-20 13:56:53
【问题描述】:

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

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

但是在我的*ngFor-Element 中,我需要在我的books-Array 中查找,其中id 等于我的booksDisplay-Array 中的当前bookId。那么如何在*ngFor-Element 中使用类似 where 子句的内容呢?

【问题讨论】:

  • 您可以在您的组件中创建一个字典/查找属性,其中键是书籍 ID,并在 *ngFor 块内引用它。或者您可以将 2 个数组合并为一个数组并对其进行迭代。
  • 在我看来,您应该使用 component.ts 中的方法来过滤这些书籍,然后在 UI 中查找这些书籍。让 UI 进行简单的渲染会提高您的性能。
  • 能否请您在stackblitz.com/edit/angular-xcgx1h中举例子
  • 添加数组的结构。

标签: html arrays angular ngfor


【解决方案1】:

这样的事情应该可以工作。但是,我最好在模型中准备数据,而不是在模板中进行此类计算..

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

【讨论】:

    【解决方案2】:

    假设您的 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>
    

    【讨论】:

    • 谢谢。但这对我不起作用,因为索引不是书名。一本书在 booksDisplay 数组中有多个元素....还有其他方法可以解决这个问题吗?
    • 我觉得我误解了你的问题。您能否提供一小部分您试图筛选的数据样本?我可以相应地编辑我的答案。
    【解决方案3】:

    像这样; 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> 
    

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2016-11-17
      相关资源
      最近更新 更多