How to filter mat card in angular

Viewed 1559

I'm wondering how I can use the search bar(https://stackblitz.com/edit/stackoverflowcom-a-60857864-6433166-dpaump ) and the code below to be able to filter the cards using it name.

This is my Explore TS file (I imported matcards and routers components from different files)

import { Router } from '@angular/router';
import { WorkspaceService } from 'src/app/core/services/workspace.service';
import { Workspace, WorkspaceType } from 'src/app/shared/models/workspace.model';

And this is inside HTML file to display the cards

 <mc-workspace-card-list [workspaces] = "pubWorkspaces" [editable] = "false"></mc-workspace-card-list>   

And this is what it look like right now

[![enter image description here][1]][1]

Note: I did not included the code above in my Stackblitz file because there are alot of components involved and I'm wondering if someone can help me or give me tips on how to implement this filter function for cards by just looking the code above and stackblitz file.

2 Answers

Citrus punk's answer works but here is some explanation

HTML:

<input type="text"
[(ngModel)]="searchText" (ngModelChange)="searchTextChanged($event)" />

Ts:

In ngOnInit After this forEach store copy pubWorkspaces in separate array

   workspaces.forEach(workspace => {
        if(workspace.type == WorkspaceType.public){
          this.pubWorkspaces.push(workspace);
        }
      });
   this.filteredPubWorkSpaces= this.pubWorkspaces;

Below function gets called when there is change in search and im assuming you have name property in pubws object.

searchTextChanged(searchText){
 //return array of workspace only having search text in their names
  this.filteredPubWorkSpaces= this.pubWorkspaces.filter(pubws=>pubws.name.includes(searchText));
}

Pass it to component

 `<mc-workspace-card-list [workspaces] = "filteredPubWorkSpaces" [editable] = "false"></mc-workspace-card-list>`

You could make an additional list that is showing the results. Just copy the full list when initializing the component. On the searchbar change event you can call a function that filters the original list with the searchterm and save this to an extra variable:

export class ExploreComponent implements OnInit, OnDestroy {

private workspaces;
public filteredWorkspaces;
public searchterm;

constructor(private workspaceService: WorkspaceService, private router: Router) { }


ngOnInit(): void {

    this.loading = true;
    this.workspaceService.getUserWorkspaces().subscribe((workspaces) =>{

    workspaces.forEach(workspace => {
      if(workspace.type == WorkspaceType.public){
        this.pubWorkspaces.push(workspace);
      }
    this.filteredWorkspaces = workspaces;
}

onInputChange(){
    this.filteredWorkspaces = this.workspaces.filter(ws => ws.name.includes(this.searchterm));
}
Related