2017-12-31 231 views
0

ngFor項目をフィルタリングする入力があります。
フィルタを適用した後に実際に存在する行の量を示すインデックスを指定します。内部5 ngの内部 - インデックスを実際に含まれる行に変更します

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

あなたがフィルターに「ボブ」を入れた場合、結果は実際のインデックスをカウントされますが、私は、現在の項目の実際のインデックスをしたいです。 これが実際の結果です。

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

+0

なぜあなたは、単に結果のフィルタ項目を使用して新しいリストを生成いけませんか? –

答えて

0

私はあなたが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))]; 
    } 
} 
関連する問題