components icon indicating copy to clipboard operation
components copied to clipboard

mat-select - Allow mat-option selected property to be settable

Open djarekg opened this issue 9 years ago • 23 comments

Bug, feature request, or proposal:

Feature request

What is the expected behavior?

To be able to set the mat-option selected property

What is the current behavior?

Currently the mat-option selected property is readonly and you have to programatically select options.

What is the use-case or motivation for changing an existing behavior?

Being able to bind to the selected property would be a cleaner implementation for a user versus having to do it manually, especially in cases where using cascading mat-select with multiple=true (harder to manage)

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular 4.4.3 Material 2.0.0-beta.11 Windows 10 TypeScript - 2.5.2 All browsers

djarekg avatar Sep 22 '17 10:09 djarekg

This is what I'm doing:

HTML

<mat-form-field>
            <mat-select #thisselect placeholder="Brands" formControlName="brands"
                (selectionChange)="selectChanged($event)" multiple required>
                <mat-option *ngFor="let brand of brandList; index as i" [value]="i">{{brand.name}}</mat-option>
            </mat-select>
        </mat-form-field>

Typescript

@ViewChild('thisselect', {static: false}) thisselect: MatSelect;

ngAfterViewInit() {
    setTimeout(() => {
     // because the "[value]=" in the html is set to i (index)
     // we can set which items we want selected simply by using the index
      this.thisselect.value = [0, 2];
    }, 1);
  }

PostImpatica avatar Oct 25 '19 16:10 PostImpatica

This is what I'm doing:

HTML

<mat-form-field>
            <mat-select #thisselect placeholder="Brands" formControlName="brands"
                (selectionChange)="selectChanged($event)" multiple required>
                <mat-option *ngFor="let brand of brandList; index as i" [value]="i">{{brand.name}}</mat-option>
            </mat-select>
        </mat-form-field>

Typescript

@ViewChild('thisselect', {static: false}) thisselect: MatSelect;

ngAfterViewInit() {
    setTimeout(() => {
     // because the "[value]=" in the html is set to i (index)
     // we can set which items we want selected simply by using the index
      this.thisselect.value = [0, 2];
    }, 1);
  }

Hi @helzgate, Is there a way that instead of the index we can select them by the item's value? The index is repeated for each group iteration I believe. So all the groups start from 0, 1, 2 ... It cannot select other groups' items by index.

efronic avatar Feb 13 '20 03:02 efronic

If you're using autocomplete along with chips as in the official example https://material.angular.io/components/chips/examples#chips-autocomplete there is no compareWith input

azerafati avatar Jan 09 '24 13:01 azerafati