javascript Angular 4 Filter搜索自定义管道

vptzau2j  于 4个月前  发布在  Java
关注(0)|答案(7)|浏览(71)

因此,我尝试构建一个自定义管道来在ngFor循环中搜索多个值的过滤器。我已经寻找了许多小时来寻找一个好的工作示例,其中大多数都是基于以前的构建,似乎不起作用。因此,我正在构建管道并使用控制台给我给予值。然而,我似乎无法让输入文本显示出来。
以下是我之前寻找工作示例的地方:
Angular 4 Pipe Filter
http://jilles.me/ng-filter-in-angular2-pipes/
https://mytechnetknowhows.wordpress.com/2017/02/18/angular-2-pipes-passing-multiple-filters-to-pipes/
https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview
https://www.youtube.com/results?search_query=filter+search+angular+2
https://www.youtube.com/watch?v=UgMhQpkjCFg
下面是我目前拥有的代码:
component.html

<input type="text" class="form-control" placeholder="Search" ngModel="query" id="listSearch" #LockFilter>

      <div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | LockFilter: query">
        <input type="checkbox" ngModel="lock.checked" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
        <label for="{{lock.ID}}" class="check-label"></label>
        <h3 class="card-text name" ngModel="lock.name">{{lock.User}}</h3>
        <h3 class="card-text auth" ngModel="lock.auth">{{lock.AuthID}}</h3>
        <h3 class="card-text form" ngModel="lock.form">{{lock.FormName}}</h3>
        <h3 class="card-text win" ngModel="lock.win">{{lock.WinHandle}}</h3>
      </div>

字符串
pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'LockFilter'
})

export class LockFilterPipe implements PipeTransform {
  transform(locked: any, query: string): any {
    console.log(locked); //this shows in the console
    console.log(query); //this does not show anything in the console when typing
    if(!query) {
      return locked;
    }
    return locked.filter((lock) => {
      return lock.User.toLowerCase().match(query.toLowerCase());
    });
  }
}


我已经将管道导入模块。
我对Angular 4还是比较新的,我正在努力弄清楚如何使它工作。无论如何,感谢您的帮助!
我想我需要更具体一些。我已经在JS中建立了一个过滤搜索,它不会过滤所有的选项,这就是我正在尝试做的。不仅仅是过滤用户名。我正在过滤所有4条数据。我选择了一个管道,因为这是Angular建议你做的,因为他们最初在AngularJS中使用它们。我只是试图从本质上重新创建我们在AngularJS中使用的过滤管道我发现的所有选项都不起作用,或者来自Angular以前的版本。
如果你需要我的代码中的任何东西,让我知道。

zc0qhyus

zc0qhyus1#

我必须在我的本地实现搜索功能,这里是更新您的代码。请这样做。
这是我需要更新的代码。

目录结构

app/
   _pipe/
        search/
          search.pipe.ts
          search.pipe.spec.ts
app/ 
   app.component.css
   app.component.html
   app.component.ts
   app.module.ts
   app.component.spec.ts

字符串

创建管道命令运行

ng g pipe search

component.html

<input type="text" class="form-control" placeholder="Search" [(ngModel)]="query" id="listSearch">
    <div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | LockFilter: query">
    <input type="checkbox" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
    <label [for]="lock.ID" class="check-label"></label>
    <h3 class="card-text name">{{lock.User}}</h3>
    <h3 class="card-text auth">{{lock.AuthID}}</h3>
    <h3 class="card-text form">{{lock.FormName}}</h3>
    <h3 class="card-text win">{{lock.WinHandle}}</h3>
</div>

component.js

注:在这个文件中,我必须使用虚拟记录的实施和测试的目的。

import { Component, OnInit } from '@angular/core';
import { FormsModule }   from '@angular/forms';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
    export class AppComponent implements OnInit{
    public search:any = '';
    locked: any[] = [];

    constructor(){}

    ngOnInit(){
        this.locked = [
            {ID: 1, User: 'Agustin', AuthID: '68114', FormName: 'Fellman', WinHandle: 'Oak Way'},
            {ID: 2, User: 'Alden', AuthID: '98101', FormName: 'Raccoon Run', WinHandle: 'Newsome'},
            {ID: 3, User: 'Ramon', AuthID: '28586', FormName: 'Yorkshire Circle', WinHandle: 'Dennis'},
            {ID: 4, User: 'Elbert', AuthID: '91775', FormName: 'Lee', WinHandle: 'Middleville Road'},
        ]
    }
}

模块.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { AppComponent } from './app.component';
import { SearchPipe } from './_pipe/search/search.pipe';

@NgModule({
  declarations: [
    AppComponent,
    SearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'LockFilter'
})

export class SearchPipe implements PipeTransform {
    transform(value: any, args?: any): any {

        if(!value)return null;
        if(!args)return value;

        args = args.toLowerCase();

        return value.filter(function(item){
            return JSON.stringify(item).toLowerCase().includes(args);
        });
    }
}


我希望你得到管道功能,这将帮助你。

l7mqbcuq

l7mqbcuq2#

简单的filterPipe for Angular 2+

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class filterPipe implements PipeTransform {

  transform(items: any[], field:string, value: string): any[] {

    if(!items) return [];
    if(!value) return items;

    return items.filter( str => {
          return str[field].toLowerCase().includes(value.toLowerCase());
        });
   }
}

字符串
这里是HTML

<input type="text" class="form-control" placeholder="Search" id="listSearch" #search>
    <div class="panel panel-default col-xs-12 col-sm-11" *ngFor="let lock of locked | filter:'propName': search.value>
    <input type="checkbox" (change)="openModal($event, lock)" class="check" id="{{lock.ID}}">
    <label [for]="lock.ID" class="check-label"></label>
    <h3 class="card-text name">{{lock.User}}</h3>
    <h3 class="card-text auth">{{lock.AuthID}}</h3>
    <h3 class="card-text form">{{lock.FormName}}</h3>
    <h3 class="card-text win">{{lock.WinHandle}}</h3>
</div>


在HTML中,PropName是虚拟文本。使用任何对象属性键代替PropName

kxxlusnw

kxxlusnw3#

按照以下代码使用自定义筛选器筛选表中的特定列而不是所有列

文件名.组件.html

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">product name </th>
      <th scope="col">product price</th>
   </tr>
  </thead>

  <tbody>
    <tr *ngFor="let respObj of data | filter:searchText">
      <td>{{respObj.product_name}}</td>
      <td>{{respObj.product_price}}</td>
    </tr>
 </tbody>
</table>

字符串

文件名.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-productlist',
  templateUrl: './productlist.component.html',
  styleUrls: ['./productlist.component.css']
})

export class ProductlistComponent implements OnInit  {

  searchText: string;

  constructor(private http: HttpClient) { }
  data: any;
  ngOnInit() {
    this.http.get(url)
      .subscribe(
        resp => {
         this.data = resp;

        }
      )
  }
}

filename.pipe.ts

创建一个类,用PipeTransform实现它,这样我们就可以用transform方法编写自定义filter。

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class PipeList implements PipeTransform {
  transform(value: any, args?: any): any {
    if(!args)
     return value;
    return value.filter(
      item => item.product_name.toLowerCase().indexOf(args.toLowerCase()) > -1
   );
  }
}

iugsix8n

iugsix8n4#

虽然我迟到了,但我希望这对某些人有帮助。我已经为Angular V6+做了一个自定义的搜索管道(目前也在16中构建)。

  • 这个管道使用正则表达式来搜索通过它传递的对象的整个数组。
  • 因为它是正则表达式,所以可以处理小写和大写。
  • 它还返回一个动态更新的搜索计数。

Stackblitz Link

  • 您也可以搜索特定的关键字。只需在下面提到的文件中更改此行。*
    pure-search.pipe.ts搜索管道**
const properties = Object.keys(item);

字符串
将其更改为

const properties = ['key1','key2','key3'] //mention the key names


请确保您传递的对象是单级别的。此筛选器已在超过3000条记录中顺利运行。

ee7vknir

ee7vknir5#

这里是简单的解释,以创建自定义管道..作为可用的管道不支持它.我发现这个解决方案here..很好地解释了它
创建管道文件advanced-filter.pipe

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'advancedFilters'
})

export class AdvancedFilterPipe implements PipeTransform {

  transform(array: any[], ...args): any {
    if (array == null) {
      return null;
    }

    return array.filter(function(obj) {
      if (args[1]) {
        return obj.status === args[0];
      }
      return array;
    });

  }

}

字符串
在这里,数组-将数据数组传递给您的自定义管道对象-将数据对象通过使用该对象,您可以添加条件来过滤数据
我们已经添加了条件obj.status === args[0],以便数据将在.html文件中传递的状态上进行过滤
现在,在组件的module.ts文件中导入并声明自定义管道:

import {AdvancedFilterPipe} from './basic-filter.pipe';

//Declare pipe

@NgModule({

    imports: [DataTableModule, HttpModule, CommonModule, FormsModule, ChartModule, RouterModule],

    declarations: [ DashboardComponent, AdvancedFilterPipe],

    exports: [ DashboardComponent ],

    providers: [{provide: HighchartsStatic}]

})


在.html文件中使用创建的自定义角管道

<table class="table table-bordered" [mfData]="data | advancedFilters: status" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy" [(mfSortOrder)]="sortOrder">

                <thead>
                       <tr>
                             <th class="sortable-column" width="12%">
                                 <mfDefaultSorter by="inquiry_originator">Origin</mfDefaultSorter>
                             </th>
                        </tr>
                </thead>

                <tbody class="dashboard-grid">

                                <ng-container *ngFor="let item of mf.data; let counter = index;">

                                                <tr class="data-row {{ item.status }} grid-panel-class-{{ counter }}">                                      

                                                                <td class="align-center">{{ item.trn_date }}</td>

                                                                <td>{{ item.trn_ref }}</td>

                                                </tr>

                </tbody>

</table>

//If you are using *ngFor and want to use custom angular pipe then below is code

<li *ngFor="let num of (numbers | advancedFilters: status">
  {{ num | ordinal }}
</li>

kfgdxczn

kfgdxczn6#

我能想到的一个简单的类似Java的逻辑,从 typescript 的Angular 看可能不是很紧凑,如下所示:

transform(value:IBook[], keyword:string) {       
        if(!keyword)
        return value;
        let filteredValues:any=[];      
        for(let i=0;i<value.length;i++){
            if(value[i].name.toLowerCase().includes(keyword.toLowerCase())){
                filteredValues.push(value[i]);
            }
        }
        return filteredValues;
    }

个字符

llmtgqce

llmtgqce7#

您可以在输入框的(input)事件上使用给定的函数

filterNames(event)
{
 this.names_list = this.names_list.filter(function(tag) {
 return tag.name.toLowerCase().indexOf(event.target.value.toLowerCase()) >= 0;
 });
}

字符串
希望有帮助。

相关问题