使用自定义管道过滤angular4中的多个列表

时间:2017-12-19 20:59:23

标签: angular

我有两个组件,在admin.component用户名中我可以过滤,在vragen.component中我无法过滤,它是相同的HTML。为什么我无法访问vragenSearch。

Angular Html

<div class="container-fluid">
            <ul>
                <div *ngFor=" let vraag of resultsvragen | sort | filter : vragenSearch; let i = index">
                <li [ngClass]="{'omkringd': vraag.username == this.dataService.UserName, 'omkringdTwee': vraag.username !== this.dataService.UserName }"  (click)="onSelect(vraag, vraag.vraagID)"
                  [ngStyle]="{'background-color':this.markeer[vraag.vraagID]? '#47d147':'none'}">
                   {{vraag.username+": "}} {{vraag.tekst}}
                   <div *ngIf="!this.upvote[vraag.vraagID]">
                        <button class="btn btn-success" (click)="Upvote(vraag.vraagID)"><i class="fa fa-heart-o" aria-hidden="true"></i></button>
                    </div>

Angular Html

 <ul>
            <div *ngFor="let user of allUsers | filter : usersSearch; let i = index">
            <li>
                {{ user.voornaam + " : " }}  
                <div *ngIf="user.leerkracht">Admin</div>
                <div *ngIf="!user.leerkracht">
                    Geen admin    
                    <button class="btn btn-sm btn-primary" name="maakAdminButton" (click)="maakAdmin(user.id)">Maak admin</button>
                </div>
            </li>
        </div>
        </ul>

角度过滤管

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filter'
})
export class FilterPipe implements PipeTransform {
    transform(items: any[], usersSearch: string, vragenSearch: string){
        if (items && items.length){
            return items.filter(item =>{
              if (usersSearch && item.voornaam.toLowerCase().indexOf(usersSearch.toLowerCase()) === -1){

                    return false;
                }
                if (vragenSearch && item.tekst.toLowerCase().indexOf(vragenSearch.toLowerCase()) === -1){
                    return false;
                }
                return true;
           })
        }
        else{
            return items;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据您的代码段,您尝试将两个不同的搜索参数传递给过滤器管道。请注意,参数未命名!

只有参数的顺序很重要。在这里检查多个管道参数的用法: https://angular-2-training-book.rangle.io/handout/pipes/using_pipes.html

所以即使你有这个代码:

let user of allUsers | filter : vragenSearch;

vragenSearch的值仍将作为usersSearch传递到您的过滤器管道中。 https://v2.angular.io/docs/ts/latest/guide/pipes.html