所以我正在尝试构建一个自定义管道来对ngFor循环中的多个值进行搜索过滤。我已经花了好几个小时才找到一个好的工作示例,其中大多数是基于以前的版本,似乎没有用。所以我正在构建Pipe并使用控制台为我提供值。但是,我似乎无法显示输入文本。
以下是我以前寻找工作示例的地方:
http://jilles.me/ng-filter-in-angular2-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个数据。我选择了一个Pipe,因为这是Angular建议你做的,因为他们最初在AngularJS中使用它们。我只是想尝试基本上重新创建我们在AngularJS中为了性能而移除的过滤管道。我发现的所有选项都不起作用,或者来自以前的Angular版本。
如果您需要我的代码中的任何其他内容,请告诉我。
答案 0 :(得分:11)
我必须在我的本地实现搜索功能,这里更新了您的代码。请这样做。
以下是我必须更新的代码。
目录结构
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'},
]
}
}
<强> module.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);
});
}
}
我希望你能获得管道功能,这对你有帮助。
答案 1 :(得分:1)
遵循此代码以使用自定义过滤器过滤特定列而不是表中的所有列
filename.component.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>
filename.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 方法编写自定义过滤器。
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
);
}
}
答案 2 :(得分:0)
适用于Angular 2+的简单filterPipe
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 来使用您的任意对象属性键。
答案 3 :(得分:0)
这里是创建自定义管道的简单说明。由于可用管道不支持该管道。 我找到了这个解决方案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 –将成为数据的对象,通过使用该对象,您可以添加条件以过滤数据
我们添加了条件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>
答案 4 :(得分:0)
我想到的一个简单的类似Java的逻辑在打字稿方面可能看起来并不紧凑:
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;
}
<h2>Available Books</h2>
<input type="text" [(ngModel)]="bookName"/>
<ul class="books">
<li *ngFor="let book of books | search:bookName"
[class.selected]="book === selectedBook"
(click)="onSelect(book)">
<span class="badge">{{book.name}}</span>
</li>
</ul>
答案 5 :(得分:-2)
您可以在输入框的(输入)事件中使用给定的功能
filterNames(event)
{
this.names_list = this.names_list.filter(function(tag) {
return tag.name.toLowerCase().indexOf(event.target.value.toLowerCase()) >= 0;
});
}
希望有所帮助......