Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all the options. In addition, I want the value in the FormControl to be set as ALL if this option is chosen, otherwise it should reflect the user's selections.

To experiment with a potential solution, I have created a project on Stackblitz, which can be accessed through this link.

Any insights on the best approach to achieve this? I understand that typically, dropdown menus display the label of the selected option in the view.

Answer №1

In the example provided by Angular Material for customizing trigger text in selects, they demonstrate the use of the mat-select-trigger directive to define the text displayed on the select trigger:

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppings" multiple>
    <mat-select-trigger>
      @if (toppings.value?.length === toppingList.length) {
        <span>ALL</span>
      } @else {
        {{toppings.value?.[0] || ''}}
        @if ((toppings.value?.length || 0) > 1) {
          <span class="example-additional-selection">
            (+{{(toppings.value?.length || 0) - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
          </span>
        }
      }
    </mat-select-trigger>
    @for (topping of toppingList; track topping) {
      <mat-option [value]="topping">{{topping}}</mat-option>
    }
  </mat-select>
</mat-form-field>

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

What is the best way to transform JSON or an array from an AJAX responseText into a JavaScript array?

I recently implemented ajax into my code, and it is working perfectly. It provides me with either JSON or an array as the output. Here is the snippet of code I used: xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","http://map_ajax_control.php",false); xm ...

App-Root in Angular 2 not loading properly in ExpressJS route

As a newcomer to NodeJS and Express, I am trying to create a simple '/' route that points to Angular's default index.html file located at client/src/index.html. This file contains the app-root tag. While the '/' route successfully ...

How to effectively utilize signed requests for AWS S3 when uploading images?

My project involves developing a react native application similar to Slack, and I'm currently facing an issue with image uploads to S3. I decided to use the getSignedUrl route for this functionality. The process goes as follows: the client selects a ...

What is the integration between redux and next.js like?

I am currently trying to integrate Redux into an existing Next.js project, but I am struggling to grasp how the store functions server-side. I came across this example that I am following: https://github.com/vercel/next.js/blob/canary/examples/with-redux ...

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

A more efficient way to have Vue import files from the assets folder rather than manually inserting script tags into the index.html file

I have a simple structure and would like to utilize assets from cdnjs.com in my project. The issue arises when I try to import these assets from src/assets/lib instead of directly from the CDN. For example, importing jQuery like this: Main.js: import &a ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Utilize array.prototype.reduce() with strings

I'm puzzled about how the reduce operation is carried out on a string. Initially, a new Str instance is created with the desired string as a parameter. Following that, the split method is used to divide the string into an array of strings. A method c ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...

Issue with Angular: Unable to properly sort data while modifying queryParams

Within the component.ts file: export class TabsComponent implements OnInit { constructor( private store$: Store<UsersState>, private router: ActivatedRoute ) {} ngOnInit(): void { this.onFilterByIncome(); this.router.queryParam ...

Detecting when the page is done loading in CasperJS with the help of $.ajaxStop()

During my CasperJS tests, I've relied on waitForSelector() to check if a page has finished loading, including all asynchronous AJAX requests. However, I'm interested in finding a more standard approach for waiting for page load. Is it possible to ...

"In a single line, add an item to an array based on a specified condition

I am trying to achieve something similar in JavaScript with a one-liner. Can this be done without using an if statement? // These versions add false to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = awai ...

Proper method for displaying modifications in QueryList from @ContentChildren

I'm having trouble with rendering components and here is the code snippet: <my-component> <ng-template *ngFor="let item of data"> <child-component> <div> {{ data.title }} </div> </child-c ...

The folder creation in the 'outDir' directory by TSC continues to grow

Hello! Currently, I am engaged in a small TypeScript project where I need to utilize two separate tsconfig.json files, both of which inherit from my main tsconfig.base.json file. Unfortunately, I encountered an issue with the compiler creating unnecessar ...

Establish a connection between an Angular Docker container and an Asp.Net container

A program was developed with three main components: a database (MS SQL Server), backend (Asp.Net Core), and frontend (Angular 8). The program is run using docker-compose: services: sqlserver: image: mcr.microsoft.com/mssql/server:2019-latest ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

Can the `XMLHttpRequest` object stay active when the user switches to a different page?

I am currently facing an issue on my website where users can submit a form using AJAX. The response is displayed in an alert indicating whether the submission was successful or if there were any issues. However, due to the asynchronous nature of this proce ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Creating a showcase page that generates its own code: A guide

If you have created a demo page for your product and want to include a button at the bottom that, when clicked, displays the source code of the demo above, how can you accomplish this in an elegant way? ...

ngOnChanges fails to trigger

I have set up a StackBlitz example (without server side code) which demonstrates an issue with reassigning a variable asynchronously from the backend. I need to update these values so that all objects in the array are of the same type for use in a select ...