You can create a pipe for this.
Here is a working solution
I created a pipe and called it 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) : [];
}
}
And simply use it within *ngFor
as follows
<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>
Also, added and input and output to search.component
so that we can update our 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>