Search code examples
htmlcssangularfiltermat-card

How to filter mat card in angular


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.


Solution

  • 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>`