Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple mat-select start with all checked?

I have a dinamicly mat-select in an Angular4 app. What I need is: when I fill the mat-select options, I need to set all the options as checked. I tried many thins but no one worked. Please help.

This is what I got:

ts:

options = {
    0: 'op1',
    1: 'op2',
    2: 'op3',
    3: 'op4'
  };

but the options variable can change. Sometimes the length can be 5, sometimes can be 16, sometimes 0, that is dinamic.

Then, in my HTML i got this:

<mat-select multiple placeholder="Options" required="true" [(ngModel)]="selected-options">
  <mat-option *ngFor="let op of options" [value]="op">{{ op }}</mat-option>
</mat-select>

Look the multiple in the mat-select tag.

THIS WORKS! but that just set the options in the select and the value is unchecked.

So... how can I set all the items checked?

like image 386
Sergio Mendez Avatar asked Jul 23 '18 22:07

Sergio Mendez


People also ask

How do you add select all in mat-select?

After completing the installation, Import 'MatSelectModule' from '@angular/material/select' in the app. Then use <mat-select> tag to group all the items inside this group tag.

What is Mat Optgroup for?

The <mat-optgroup> element can be used to group common options under a subheading. The name of the group can be set using the label property of <mat-optgroup> . Like individual <mat-option> elements, an entire <mat-optgroup> can be disabled or enabled by setting the disabled property on the group.

How do I set mat-option selected by default?

Just for information, you need to make sure the datatype of the default value matches with that of the options, for.eg, <mat-select [(value)]="heroes[0]. id"> <mat-option *ngFor="let hero of heroes" [value]="hero.id">{{ hero.name }}</mat-option> </mat-select> will work.

What is Mat-Select trigger?

MatSelectTrigger. Allows the user to customize the trigger that is displayed when the select has a value.


1 Answers

Try this:

HTML:

<mat-select multiple placeholder="Options" required="true" [formControl]="selectedOptions">
  <mat-option *ngFor="let op of options" [value]="op">{{ op }}</mat-option>
</mat-select>

In your TS:

options: string[] = {'op1','op2','op3','op4'};
selectedOptions = new FormControl(this.options);
like image 97
KimCindy Avatar answered Oct 10 '22 10:10

KimCindy