角度6中的搜索过滤器

Emp*_*oul 2 typescript angular angular6

我有两个组件,分别称为listdetails,单击list-item列表中的特定组件。它将发出选定/单击list-itemdetails组件,如下图所示。

在此处输入图片说明

现在,我在该组件search上方放置了另一个组件,list如下所示:

在此处输入图片说明

如何为列表组件中的当前内容应用过滤器?这样我就可以轻松搜索。list-itemslist-items

Stackblitz链接

Bun*_*ner 7

您可以为此创建一个管道。

这是一个可行的解决方案

我创建了一个管道并命名为 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) : [];
  }

}
Run Code Online (Sandbox Code Playgroud)

并在*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>
Run Code Online (Sandbox Code Playgroud)

另外,添加并输入和输出到,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);
  }

}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)