Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to set default value in Material Multiselect Angular 6

I am trying to implement a multiselect in Angular using Material.

When the page is opened in Edit mode, some of the types should be selected as default in the Multiselect but it is not working in my case.

Below is the HTML:

 <mat-form-field >
      <mat-select  placeholder="DocTypes" [(value)]="selectedDocType" formControlName="docTypes" multiple>
        <mat-option  *ngFor="let doc of docs" [value]="doc.name">{{doc.name}}</mat-option>
      </mat-select>
    </mat-form-field>

And I am filling SelectedDocType as below:

  selectedDocType: string[] = new Array();
 resp.forEach(x => {
                    this.selectedDocType.push(x.name);
                  });

Here resp contains correct doc type. For example CV.

Weired thing is when I set the selectedDocType as below then it works:

this.selectedDocType = ["CV"];

But it does not work when I push under the for each as I mentioned above. Both of them is having 1 value in the array.

What am I doing wrong?

Update: Doc format is as below:

export interface DocTypes{
  id: string;
  name: string;
}
like image 324
Neel Avatar asked Jan 23 '26 20:01

Neel


1 Answers

The problem is a known issue with material select. It selects by object reference and not by value.

  • which is why it works with just strings but fails with actual objects...

You can quite easily override that behavior using a built-in input compareWith

Here's a little stackblitz demo for you to get the concept:

HTML:

<mat-form-field>
  <mat-select multiple [(ngModel)]="selectedObjects" [compareWith]="comparer">
    <mat-option *ngFor="let iobject of allObjects" [value]="iobject">{{iobject.name}}</mat-option>
  </mat-select>
</mat-form-field>

Component:

interface obj {
  name: string,
  value: number
}

@Component({
  selector: 'select-multiple-example'
})
export class SelectMultipleExample {

  selectedObjects : obj[];

  allObjects : obj[] = [
    {name: 'AAA', value: 1},
    {name: 'BBB', value: 2},
    {name: 'CCC', value: 3}
  ];
  
  ngOnInit() {
    // define default selection
    this.selectedObjects = [{name: 'AAA', value: 99}, {name: 'CCC', value: 99}];    
  }

  comparer(o1: obj, o2: obj): boolean {
    // if possible compare by object's name property - and not by reference.
    return o1 && o2 ? o1.name === o2.name : o1 === o2;
  }
}
like image 147
Stavm Avatar answered Jan 26 '26 12:01

Stavm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!