Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在不丢失索引的情况下筛选数组?_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 如何在不丢失索引的情况下筛选数组?

Javascript 如何在不丢失索引的情况下筛选数组?,javascript,angular,typescript,Javascript,Angular,Typescript,app.component.html <div class="input-group"> <input type="text" #searchBox class="form-control chapter-filter" placeholder="Search chapter..." name="chapter" [(ngModel)]="searchText"

app.component.html

<div class="input-group">
<input type="text" #searchBox class="form-control chapter-filter" placeholder="Search chapter..." name="chapter" [(ngModel)]="searchText" />
}

问题是,当我过滤任何章节时,它工作正常,但章节索引是根据过滤的章节设置的。
--> 假设我有三章

  • 一(索引-0)
  • 二(指数-1)
  • 三(指数-2)
  • 当我输入三个时,它只显示三个。没错,但现在它的指数是0。
    如何使其保持索引2。我的意思是它应该过滤,但不应该改变索引。

    这里有几个选项

  • 将章节传递给单击处理程序
  • 使chapterIndex成为
    章节的属性

  • 为什么不把
    章索引
    作为
    章的属性
    ?如果你不想这样做,我认为你不应该使用searchFilter管道,而是在你的组件中使用过滤逻辑,使用allChapters和filteredChapters数组。但问题是我在
  • 标记中有一些需要索引的东西。这需要索引。有没有什么方法可以让我也过滤并保持索引不变initialy@Karan是的,选择2。谢谢@Hansmad,选项2很好用。
    transform(items, searchText, searchField: string) {
    let filteredList = [];
    if (searchText) {
        return items.filter(item => {
            searchText = searchText.trim().toLowerCase();
            let itemName = item[searchField].trim().toLowerCase();
    
            if (itemName.indexOf(searchText) > -1) {
                filteredList.push(item);
                return filteredList;
            }
        })
    } else {
        return items;
    }
    
    <li (click)="changeChapter(chapter)" *ngFor="let chapter of chapters | searchFilter">
    
    changeChapter(chapter) { 
       this.chapterIndex = this.chapters.indexOf(chapter);
      // and whatever ...
    }
    
    <li (click)="changeChapter(chapter)" *ngFor="let chapter of chapters | searchFilter">
       {{ chapter.chapterIndex }} - {{ chapter.name }}
    </li>
    
    <li (click)="changeChapter(chapter)" *ngFor="let chapter of displayedChapters">
    </li>
    
    displayedChapters: Chapter[];
    private allChapters: Chapter[];
    
    changeChapter() {
       // whatever happens here...
    }