2017-12-31 32 views
0

ngFor 항목을 필터링하는 입력이 있습니다.
필터를 적용한 후에 실제로 존재하는 행의 양을 나타내는 인덱스를 원합니다. 각도 5 - 내부 포함 - 인덱스를 실제 포함 된 행으로 변경하십시오.

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