【问题标题】:Angular 5 ngIf inside ngFor - change the index to the actual included rowsngFor 内的 Angular 5 ngIf - 将索引更改为实际包含的行
【发布时间】:2018-06-11 05:11:12
【问题描述】:

我有一个过滤 ngFor 项目的输入。
我希望索引指示应用过滤器后实际存在的行数。

https://stackblitz.com/edit/angular-rwf5fa?file=app/app.component.ts

如果您将“bob”放在过滤器中,结果将计算实际索引,但我想要当前项目的实际索引。 这是实际结果。

3 = bobby
4 = bob
5 = bob the builder

这就是我想要的:

0 = bobby
1 = bob
2 = bob the builder

组件:

  @Component({
          selector: 'my-app',
          template: `
          <input type="search"  [ngModel]="search" (ngModelChange)="search = $event" />
          <div *ngFor="let item of myArray; let i = index">
            <span *ngIf="search == undefined ||  myArray[i].includes(search)">
            {{i}} = {{myArray[i]}}
            </span>
          </div>

          `
        })
        export class AppComponent {
          myArray = ["ronald","ron","dana","bobby","bob","bob the builder","ronald"];
          search : string;
        }

https://stackblitz.com/edit/angular-rwf5fa?file=app/app.component.ts

【问题讨论】:

  • 为什么不简单地用过滤后的项目生成一个新列表?

标签: angular


【解决方案1】:

我认为您无法覆盖ngFor 中的索引,但您可以使用过滤后的项目创建一个新数组:

https://stackblitz.com/edit/angular-ryazgz?file=app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <input type="search" #searchField [ngModel]="search" (ngModelChange)="search = $event" (keyup)="filterArray(searchField);" />
  <div *ngFor="let item of filteredArray; let i = index">
    {{i}} = {{filteredArray[i]}}
  </div>

  `
})
export class AppComponent {
  myArray = ["ronald","ron","dana","bobby","bob","bob the builder","ronald"];
  filteredArray = [];
  search : string;

  constructor() {
    this.filteredArray = [...this.myArray];
  }

  filterArray(field) {
    let searchTerm = field.value;
    this.filteredArray = [...this.myArray.filter(item => item.includes(searchTerm))];
  }
}

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2020-06-21
    • 2018-07-16
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多