Setting a true/false option with mat-select (multiselect) in Angular Material: a step-by-step guide

Using Angular Material, I implemented a multiple selection feature.

<mat-form-field>
  <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</mat-form-field>

I am looking to set some options to either true or false based on my needs, but I am not sure how to do so.

Before: https://i.sstatic.net/jc8af.png After: https://i.sstatic.net/GAjzU.png

Answer №1

When retrieving a response from an API, it will be received asynchronously.

To handle this situation, you can utilize the setValue method on either your FormControl or FormGroup instance to establish default values.

An example of how this could be implemented is shown below:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { DataService } from './data.service';

@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  toppingList: string[] = [
    'Extra cheese',
    'Mushroom',
    'Onion',
    'Pepperoni',
    'Sausage',
    'Tomato'
  ];
  selectedByDefault;
  toppings: FormControl;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.toppings = new FormControl(this.selectedByDefault);
    this.dataService.selectedValues$
      .subscribe(values => this.toppings.setValue(values));
  }

}

For further reference, here is a Functional Sample on StackBlitz.

Answer №2

An easy solution is to set default values for your form by specifying which values you want to appear as "checked" when initializing your FormGroup. Make sure that the values match exactly for it to work correctly.

Check out this functional stackblitz demo -->

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 maximum number of groupings that can be created from a set of numbers within a

I'm trying to figure out how to handle a specific task, but I'm running into some obstacles. When adding numbers to clusters, a number is considered to belong to a cluster if its distance to at least one existing number in the cluster is within a ...

Exploring JSON data in Angular

I am currently working with a Json file that contains two different objects: readers and books. Here is an example of the structure: { "users": [{ "id": 1, "username": "peterB", }, { "id": 2, "username": "MaryC" ...

instructions on activating previous and next button in pagination using material angular

In my exploration of material angular pagination, I encountered an issue where the pagination buttons get disabled when retrieving data in chunks from the backend. For instance, with 7 records and a table set to display 5 items on the first page and 2 on t ...

Exploring React Router along with Protected Route and onboarding features

I recently developed a React application with a Signin process, onboarding flow, and a dashboard. The onboarding process consists of two pages: org-creation and invite-member. Sign in functionality is managed by Aws Amplify and includes Google sign-in. Bel ...

Can you please provide the Typescript type of a route map object in hookrouter?

Is there a way to replace the 'any' type in hookrouter? type RouteMap = Record<string, (props?: any) => JSX.Element>; Full Code import { useRoutes, usePath, } from 'hookrouter' //// HOW DO I REPLACE any??? type RouteMap = ...

Exploring the ngModel directive implementation within a text input field

I'm facing an issue with displaying data in input forms. <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text text-white" style="background-color:#03a9f4">Product ID</span& ...

Ang 12 unit test failure: Unable to run 'append' on 'FormData': the second parameter is not a 'Blob' type

I am currently working on writing a unit test for the component method, but I keep encountering this error: TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'. Despite my efforts, none of ...

The React.FC component encountered an invalid hook call

I've encountered an issue while using TypeScript and trying to implement a hook within React.FC. Surprisingly, I received an error message stating that hooks can only be used inside functional components. But isn't React.FC considered a functiona ...

Experiencing problems with the Locale setting when utilizing the formatNumber function in Angular's core functionalities

I am having trouble formatting a number in Angular using the formatNumber function from the Angular documentation. Here is my code snippet: import {formatNumber} from '@angular/common'; var testNumber = 123456.23; var x = formatNumber(Numb ...

"Encountering a build failure in Next.js when using getStaticProps because a parameter is returning undefined

An unusual error has recently surfaced, causing our builds to fail, Located within the pages directory is a post/[id].tsx file that utilizes getStaticProps and getStaticPaths -- props export const getStaticProps: GetStaticProps = async ({ params }) => ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

When working with React and TypeScript, avoid using {} as a type declaration. Instead, choose more specific type definitions

While working with React and TypeScript in my Contact component, I encountered an ESLint error indicating that using {} as a type is not recommended. The message clarified that {} actually means "any non-nullish value." It's worth noting that the com ...

A notification pop-up will only appear the first time after sending a repeated action

When testing my snackBar functionality by inputting incorrect user credentials multiple times and submitting the form, I encountered an issue. The snackBar only appears the first time, not every time an error or success message is dispatched. Below is the ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Leveraging Global Functions with Angular 5

I am faced with the challenge of integrating video.js into my IonicFramework application built using Angular. I attempted to install it via npm, but encountered issues with TypeScript recognizing any importable module, and was unable to find clear document ...

Accessing component variables within an event in Angular 2 (dealing with scope problems)

I am currently facing an issue with scoping in my component click event. Specifically, I need to access private variables within the component, but the keyword this now refers to the event scope rather than the component's. This has led to an error wh ...

Using TypeScript to Limit the Generic Type Parameter Passed into a Function

I am working with a generic interface that has specific constraints applied to its parameters. Here is an example of how it is used: interface Fetcher<Params,Resp> { fetch(params: Params): Resp; }; In my code, I have a function that uses this inte ...

Using Bootstrap and Angular4 for pagination on a div or table

In my Angular4 project, I have a collection of "cards" that I want to display on the page in sets of 6. However, traditional table pagination doesn't work for these cards since they don't fit neatly into rows and columns like table data does. Her ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

In my Angular project, I'm currently working on retrieving a boolean value from a service. However, I'm encountering an issue where the

I'm currently working on a basic functionality that determines whether I am a part of a team or not, providing a simple true or false response. The backend validation has been successfully completed; however, the issue lies within my angular applicati ...