Effective ways to sort material cards in Angular

Can someone guide me on how to implement a search bar in my Angular application to filter cards by name? Here is the link to my Stackblitz project for reference: https://stackblitz.com/edit/stackoverflowcom-a-60857864-6433166-dpaump

Below is a snippet from my Explore TS file where I have imported matcards and routers components from separate 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';

Here is the HTML code snippet to display the cards:

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

Here is a preview of how it looks currently:

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

Kindly note that I have not included the complete code in my Stackblitz file due to multiple components being involved. Any suggestions or assistance on how to implement the filter function for filtering cards based on name would be greatly appreciated by just analyzing the provided code and Stackblitz file.

Answer №1

Although Citrus punk's answer is effective, here is a detailed explanation:

HTML:

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

Ts:

Within the ngOnInit lifecycle hook, iterate through the workspaces array and store public workspaces in a separate array:

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

The following function is triggered when there is a change in the search input, assuming each public workspace object has a 'name' property:

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

Finally, pass the filtered public workspaces to the component:

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

Answer №2

To enhance user experience, consider displaying search results in an additional list. Simply duplicate the original list during component initialization. When the search bar content changes, implement a function to filter the original list based on the search term and store the filtered results in a separate 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));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

Is it feasible to programmatically click a div button in C# using WebBrowser?

Exploring the capabilities of WebBrowser in C#, I came across a website that features a button without an ID, but rather nested within a div element. <div class="pc-image-info-box-button-btn-text pc-cursor"><i class="fa fa-heart" aria-hidden="tru ...

Angular select element is not functioning properly with the `addEventListener` method

My current project involves creating a table using the primeng library. The table consists of three rows and three columns, and all the data is static. Even though I am utilizing an external library, I find myself traversing the DOM directly. <p-table ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

The bold horizontal line in HTML tables is a bit unusual and is caused by the border-collapse property

Edit 1: The strange issue appears to be related to the border-collapse property in CSS, as it can be resolved by using border-spacing: 0px. However, the question remains, why does border-collapse result in this behavior? It seems to be connected to scaling ...

Responsive background styling with CSS

I'm currently learning how to create responsive websites, and I've encountered an issue. When I resize the website horizontally to a point just before the edge of the screen touches one of the elements, the background also shrinks, leaving white ...

Troubleshooting Angular 2 Submodule Import Problem

I am facing an issue with a submodule that is using NgSemanticModule. The submodule works fine without the NgSemantic tags inside its components' templates, but fails when trying to use NgSemantic Components within the submodule. Interestingly, if I u ...

When the submit button on the signup form is pressed, two distinct actions are activated to achieve specific outcomes

I am seeking assistance in implementing code that will trigger the following action: Upon clicking the 'Submit' button on a signup form after the subscriber enters their email address and name, the signup page should reload within the same tab wi ...

Guide on embedding a module into another module

I created a component called barchar. There is another module component located at src\app\modules\dashboard\page and this file contains the module. However, barchzt does not have the module. How can I utilize barchzt in the src&bsol ...

Vue.js - dynamically applying CSS classes based on conditions

Within a VueNative project that utilizes NativeBase as a component library, with tags prefixed by nb-, the code snippet below is found within the <template> tags of the footer.vue file which houses navigation buttons. This piece of logic successfully ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

Acquiring the url identifier along with parameters using the ActivatedRoute in Angular 2

I am attempting to retrieve a UUID from the URL (which is in the format of where uuid goes) and then utilize that UUID for an HTTP GET request. Currently, my app.component.ts appears as follows: private cardUuid: string; constructor(private service: App ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...

Loading a .css file in advance using NextJS

We have integrated NextJS and Material-UI into our website, but we are facing an issue with FOUC (Flash of Unstyled Content) upon page loading. After some investigation, I discovered that the JS files are loading faster than the CSS file, causing the probl ...

Change to a dark theme using React hooks in typescript

Hello, I am new to React and English is not my first language, so please excuse any mistakes. I have been trying to enable a dark mode feature on my website. Most examples I have found involve toggling between dark and light modes where you need to specify ...

Issue with Bootstrap Carousel: all elements displayed at once

I'm in the process of building a carousel. I have set up the structure, but I only want five blocks to be visible initially, with the sixth block appearing after clicking an arrow. How can I achieve this? My strategy: (adopted from here) img{ b ...

embedding data from a dictionary into a table within a Django template

Recently, I delved into the realm of Django templates for the first time. My aim was to incorporate a table into my webpage, populated with values from a dictionary that I constructed by fetching data from an API. Let me show you how I passed the data in ...

Tips for aligning content at the bottom center of a design

Could you assist me in positioning the buttons at the bottom center of the horizontal layout as depicted in the image below? Ps: the vertical layout at the top has a dynamic height. My HTML code is as follows: <html> <body> <div class="c ...