Show the distinct values of a mat-select element that retrieves information from an Angular filtered dataSource

Working on an Angular 9 app where data is displayed using a mat-table and filtered based on certain fields. The issue I'm facing is that the dropdown menu shows duplicate values, which is expected since some values may be repeated in the dataset. The data displayed is from a mat-table dataSource.filteredData, so using new Set() or similar methods is not an option. How can I modify my code to show only unique values in the dropdown?

Here is a snippet of my code:

<mat-form-field appearance="fill">
    <mat-label>Select an option</mat-label>
    <mat-select>
        <mat-option *ngFor="let country of dataSource.filteredData">{{country.name}}</mat-option>
    </mat-select>
</mat-form-field>

...

<table>
...
</table>

Note: I attempted to create a Pipe for uniqueness, but it only works effectively for static Arrays, and my Array changes with each filter. Any suggestions on how to tackle this issue? Thank you for your assistance 😊

Answer â„–1

I have successfully found a working solution by refactoring the ngFor code and implementing a function that generates an array with unique values.

To begin, I created a function that produces the non-repeated array:

// This method requires only the name of the field/key you wish to find unique values for
generateUniqueArray(field: string): string[] {
    // Initialize an empty array to store the unique values
    let uniqueArray = [];
    // Loop through the filteredData
    for (let item of this.dataSource.filteredData) {
        // Add the value of the specified field to the array
        uniqueArray.push(item[field]);
    }
    // Sort the array alphabetically
    uniqueArray = uniqueArray.sort();
    // Utilize ES6 Set to return an array with unique values
    return [...new Set(uniqueArray)];
}

For more information on Set ES6, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Refactored ngFor usage:

<mat-form-field appearance="fill">
    <mat-label>Select an option</mat-label>
    <mat-select>
        <mat-option *ngFor="let item of generateUniqueArray('country')">{{item}}</mat-option>
    </mat-select>
</mat-form-field>

Answer â„–2

Take advantage of the following ES6 functionality:

this.array = this.array.filter((value, index, array) => array.indexOf(value) === index)

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

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

Deactivating a Component in Ionic Angular

I am interested in including a CanDeactivate Guard in my Ionic Angular project. After reading about the new "CanDeactivateFn" Guard, I have been unable to find any information or examples on how to implement it. Could someone provide me with an example? ...

What is the best way to apply a custom date format of 'MM/DD/YYYY H:MM am/pm' with moment.js?

I recently started using Angular4 and moment.js to work with dates. I created a custom format: 'MM/DD/YYYY H:MM am/pm' but I'm having trouble implementing it correctly. Here is my Component.ts file: import * as moment from 'moment&apo ...

Exploring the integration of a standalone component in Angular 17 using an http service

I'm facing an issue with a standalone component: @Component({ standalone: true, // <--- See here selector: "app-login", imports: [FormsModule, CommonModule], templateUrl: "./login.component.html", styleUrl: "./lo ...

The index access type cannot be used with T[Key extends keyof T]

My work frequently involves arrays structured like this: [ {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}] and I often need to convert them into a dictionary/map format, for example: ...

Guide to building a universal model in Angular 2

How can I create a global model (class) in Angular 2? I want to be able to retrieve and set properties at any time. I attempted to achieve this as follows: export class GlobalModel { private a: number; private s: number; constructor(s: number, a ...

When considering Angular directives, which is more suitable for this scenario: structural or attribute?

In the process of developing an Angular 5 directive, I aim to incorporate various host views (generated from a component) into the viewContainer. However, I find myself at a crossroads as to whether I should opt for an attribute directive or a structural ...

Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js: import image fr ...

Navigating resolvedUrl with getServerSideProps in the newest version of NextJS - a comprehensive guide

Is there a way to obtain the pathname without using client-side rendering? I have been searching for information on how to utilize the getServerSideProps function, but so far with no luck. Initially, I attempted to employ usePathname; however, this result ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...

Limiting the number of characters in a PrimeNG Quill editor

I am currently working on implementing a maximum length for the editor. Here is the code snippet I am using: this.editorTextChange$$ = this.quillEditor.onTextChange.asObservable() .subscribe((ev) => { const limit = this.maxLength; // last cha ...

Special scenarios requiring OnPush Change Detection

I'm currently building an Angular 2 application using ngrx, and I've been intrigued by the concept of OnPush change detection for optimizing performance. After reading multiple articles on the topic, it seems that the general consensus is: "If a ...

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

Trouble with parsing JSON in rxjs ajax response

Currently, I am facing an issue while parsing a JSON string within an ajax callback in Angular2. After executing response.json()) and using console.log(), everything seems to be functioning correctly. This is the specific JSON data that I am attempting ...

What is the process for creating a coverage report for a TypeScript extension in vscode?

It appears that generating coverage reports with coveralls is not feasible for a VSCode extension built with TypeScript. Currently, I am incorporating test cases into our project https://github.com/PicGo/vs-picgo/pull/42. Despite exploring various methods ...

Dealing with Angular API Requests and Handling Cors Exception in C# Web API

My goal is to call an API on my C# Web API from my Angular Frontend. I have attempted making the call using both HTTP and HTTPS. When using HTTP, I encounter a CORS exception. On the other hand, when using HTTPS, I receive a CONNECTION CLOSED EXCEPTION. ...

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

Creating interfaces within props is essential for defining the structure of components

I'm trying to pass an Interface to one of my components, but I'm running into some issues with my approach. Here's what I have so far: import { InterfaceType } from "typescript"; type Props = { dataType: InterfaceType } export default ...

Error message displayed indicating script not found after executing yarn tsc within a Docker container

Using docker, I successfully built my project by running yarn tsc. However, when I executed docker run -p88:5011 accounts2 I encountered the following error: PM2 error: Error: Script not found: /home/accounts/dist/server/index.js. This error occurs despit ...