Madalina
Madalina

Reputation: 51

How to set an option true/false with mat-select (multiselect) Angular Material

I used a multiple selection from Angular Material .

<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 want to put some options on true or false as I want and I don't know how.

before enter image description here after enter image description here

Upvotes: 0

Views: 4194

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39452

Since the response would be coming from an API, you would receive the response asynchronously.

In that case, you can call the setValue method on your FormControl instance or FormGroup instance in order to set the values by default.

Something like this:

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));
  }

}

Here's a Working Sample StackBlitz for your ref.

Upvotes: 1

Nathan Beck
Nathan Beck

Reputation: 1191

This is a simple matter of defaulting your form values. When initializing your FormGroup, just pass in which values you'd like to show as "checked", making sure to match the values exactly.

Working stackblitz --> https://angular-r2y6gk.stackblitz.io

Upvotes: 0

Related Questions