在单击列表组件中的特定list
时,我有两个组件分别称为details
和list-item
。它将发出选中/单击的list-item
到details
组件,如下图所示。
现在,我在search
组件上方放置了另一个名为list
的组件,如下所示:
如何为列表组件中的list-items
应用过滤器?
这样我就可以轻松搜索list-items
。
答案 0 :(得分:4)
您可以为此创建一个管道。
我创建了一个管道并将其命名为ListFilterPipe
@Pipe({
name: 'listFilter'
})
export class ListFilterPipe implements PipeTransform {
transform(list: any[], filterText: string): any {
return list ? list.filter(item => item.name.search(new RegExp(filterText, 'i')) > -1) : [];
}
}
只需在*ngFor
中按如下所述使用它
<h4>List</h4>
<div class="main-div">
<app-search [(searchModel)]="searchModel"></app-search>
<div class="list">
<mat-selection-list #contact>
<mat-list-option *ngFor="let contact of contacts | listFilter: searchModel">
<a mat-list-item (click)="onSelect(contact)"><span>{{ contact?.name }}</span></a>
</mat-list-option>
</mat-selection-list>
</div>
还添加并输入和输出到search.component
,以便我们可以更新我们的searchModel
search.component.ts
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
@Input() searchModel;
@Output() searchModelChange: EventEmitter<any> = new EventEmitter();
constructor() { }
ngOnInit() {
}
updateSearchModel(value) {
this.searchModel = value;
this.searchModelChange.emit(this.searchModel);
}
}
search.component.html
<mat-form-field floatLabel=never >
<input matInput class="searching-customer" type="text" placeholder="Search"
[ngModel]="searchModel"
(ngModelChange)="updateSearchModel($event)">
</mat-form-field>
答案 1 :(得分:2)
您可以将联系人列表传递给“搜索” 对于List.component.html
中的更改<h4>List</h4>
<div class="main-div">
<app-search [list]="contacts" ></app-search>
<div class="list">
<mat-selection-list #contact>
<mat-list-option *ngFor="let contact of contacts">
<a mat-list-item (click)="onSelect(contact)"><span>{{ contact?.name }}</span></a>
</mat-list-option>
</mat-selection-list>
</div>
</div>
在搜索组件内部 -获取输入框的值 -根据输入值过滤列表
Search.component.html
<mat-form-field floatLabel=never >
<input matInput class="searching-customer" type="text" placeholder="Search" (input)="search($event.target.value)" >
</mat-form-field>
search.component.ts
import { Component, OnInit , Input} from '@angular/core';
import { IContact } from '../models';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
@Input()
public list: IContact[] ;
searchedList : any;
constructor() { }
ngOnInit() {
}
// This function will be called on every key press for input text box
search(value)
{
this.searchedList = this.list.filter(
(val)=> val['name'].includes(value))
//Searched Data
console.log(this.searchedList)
}
}