Can the tiles in a grid-list be organized in a specific order?

I am facing an issue with a class named 'scenario' that has properties such as 'id', 'name', and 'number' among others.

In the HTML, scenarios are displayed in this format:

<mat-grid-list [cols]="breakpoint" rowHeight="4:4" [@gridAnimation]="(scenarios$ | async)?.length" (window:resize)="onResize($event)">
    <mat-grid-tile *ngFor="let scenario of filteredScenarios$ | async ">
      <app-scenario-card [scenario]="scenario" [routerLink]="['/scenario', scenario.id]"></app-scenario-card>
    </mat-grid-tile>
  </mat-grid-list>

My question is, can I sort the displayed tiles of scenarios by a selected property like name, id, or number? Most resources I've found regarding sorting focus on tables or grids.

If it is possible, could someone provide me with an example or approach to achieve this?

Thank you in advance.

Also, changing from grid-list to table is not an option for me.

The 'Scenario' class has the following properties:

export class Scenario {
id: number;
scenarioName: string;
scenarioDescription: string;
periods: number; }

I already have a search box for filtering data. Now, I need help implementing a sort function for properties like id, scenarioName, and periods using buttons or dropdown menus.

The code for filtering currently looks like this:

this.scenarios$ = this.scenariosService.getScenarios();
this.filter = new FormControl('');
this.filter$ = this.filter.valueChanges.pipe(startWith(''));
this.filteredScenarios$ = combineLatest(this.scenarios$, this.filter$).pipe(
  map(([Scenario, filterString]) => Scenario.filter(scenario => scenario.scenarioName.indexOf(filterString) !== -1)));

Answer №1

Ensure that filteredScenarios$ is sorted by a specific property before passing it to the template. To achieve this, consider introducing another BehaviorSubject that will hold the sorting property.

It's challenging to provide precise code without knowing the structure of your objects, but here's an attempt:

In TypeScript:

private sortProperty$ = new BehaviorSubject<string>('name'); // set default sorting property
filteredSortedScenarios$: Observable<Scenario>

In the constructor or ngOnInt:

this.filteredSortedScenarios$ = combineLatest([this.filteredScenarios$, this.sortProperty$])
  .pipe(
    map(([scenarios, sortBy]) => {
      console.log('Sorting by', sortBy);

      return scenarios.sort((a, b) => {
        switch (sortBy) {
          case 'name':
            return a.name.localeCompare(b.name);

          case 'otherProperty':
            return ...;
        }
      });
    }));

The combineLatest function triggers when any of the Observables change, and within the map function, you can proceed with sorting the list accordingly.

To update the sorting property, simply call:

sortProperty$.next('newSortByThisProperty');

Lastly, in the template, iterate through scenarios from filteredSortedScenarios$:

<mat-grid-tile *ngFor="let scenario of filteredSortedScenarios$ | async ">

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

Angular is unable to access a service method through an observable subscription

Currently, I have a code for my service like this: cars() { return 'something here'; } Next, in order to retrieve the data using an observable from the component, I am attempting the following: getcars() { this.dataService.cars().subsc ...

While Typescript has the ability to infer recursive functions, it unfortunately cannot infer recursive types

Typescript has the ability to automatically determine the type of a recursive function: /** * Typescript correctly infers the type as * * const referencesSelf: () => ... * * This indicates recursion within the function */ const referencesSelf = () ...

Explore the world of data manipulation in Angular by experimenting with different

Embarking on a fresh Angular 2 project centered around Photos and Users. The backend work is all done, with the API in place. I've already constructed those classes. Now, I find myself pondering... To manipulate these objects on the client end, wo ...

I am looking to conceal the y-axis labels and tooltip within the react chart

I am currently working with react-chart-2. I have a line graph that displays a tooltip when hovered over, but I would like to hide this tooltip feature. Additionally, I want to remove the numbers 0, 0.1, 0.2 up to 1 on the left side (y-axis) of the gra ...

There was a Runtime Error that occurred, stating a TypeError: It is not possible to access properties of an undefined value (specifically

I've encountered an issue with a donut chart implemented from react-apex charts. Every time I try to render the page containing the chart, an error occurs. However, if I make changes to a property of the chart, it renders without any errors on the fro ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Can diff coverage be implemented for Angular 9 projects?

Currently, I am working on utilizing Angular 9 for my front end and .Net CORE for the backend. Successfully implementing differential coverage for the backend project involved the following steps: Within my azure-pipeline.yml: - task: DotNetCoreCLI@2 ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

Rendering a sanitized string with interpolation in Angular 2

After receiving the string below: "Today's product of the day is {{product_code}} !" I took this string, sanitized it to bypass security restrictions using HTML this.DomSanitizer.bypassSecurityTrustHtml(str) and inserted it into my template using ...

Developing an Angular application and deploying it onto the server

I've been working on an angular6 application and I need to create a build to test it on my server. Currently, when I use ng server, the application runs without any errors in my browser. c:\Users\emiry\Desktop\Angular\Proje ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

I am encountering a multitude of errors while trying to run the npm install

Recently, I set up Windows 11 on my new laptop and also installed Node.js and Angular Cli. However, I encountered errors when trying to run npm install in my project. Despite numerous attempts, I have been unable to resolve the issue. I have attempted var ...

Differentiating navigation design in various views of Angular 4

I am utilizing a shared navigation with content that changes via RouterModule. Is there a way to modify the design of the navigation in different views? <app-navigation></app-navigation> <router-outlet></router-outlet> For example ...

Stop the current HTTP request and initiate a new one asynchronously

My custom component showcases a detailed view of a selected building along with a list of its units (apartments). Below is the HTML code for this component: <div *ngIf="$building | async as building"> ... <div *ngIf="$buildingUnit ...

How to sort time in hms format using a MySQL query

Currently, I am facing an issue with sorting the data in MySQL in descending order based on the time for videos. Within my database, there is a Video_Duration column where video times are stored in hms format (e.g., 1h54m3s, 9m3s, 0m3s). Upon attempting ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

Watching videos is quite a time-consuming process due to the long loading times

I recently created a website at , and I am facing an issue with the homepage video taking too long to play. While it works fine on a PC, it seems to load very slowly on mobile browsers. Any suggestions on how I can improve its loading speed? <video cl ...

Setting a default value for a textfield within Angular 4

Within my for loop, I am displaying the name and price of a selected product. Users can input a quantity, with the default being 1. How can I set the text field value to default to 1? I've attempted the following method but it doesn't seem to be ...