Angular 6 Material <mat-select> multiple set default value using form control

Abhishek picture Abhishek · Jul 26, 2018 · Viewed 20.8k times · Source

I am using form control here is code for my html component

And my ts file is

export class SelectMultipleExample {
   toppings = new FormControl();
  toppingList: any[] = [
      { id:1,value:"test 1"},
      { id:2,value:"test 2"},
      { id:3,value:"test 4"},
      { id:4,value:"test 5"},
      { id:5,value:"test 6"},
      { id:6,value:"test 7"}
    ];

  

  constructor(){
    this.bindData();
  }

  bindData(){
    const anotherList:any[]=[
      { id:1,value:"test 1"},
      { id:2,value:"test 2"}
      ]

      this.toppings.setValue(anotherList)
  }
}

I want to set default value for mat select , any help how to achieve this will be great. I want to set multiple default value.

Answer

G. Tranter picture G. Tranter · Jul 26, 2018

The problem is due to the fact that your options are objects. In order for the selections to be applied, the selected objects must be the same objects as the ones used for the options. Revise your code as follows:

export class SelectMultipleExample {
    toppings = new FormControl();
    toppingList: any[] = [
        { id:1,value:"test 1"},
        { id:2,value:"test 2"},
        { id:3,value:"test 4"},
        { id:4,value:"test 5"},
        { id:5,value:"test 6"},
        { id:6,value:"test 7"}
    ];

    constructor(){
        this.bindData();
    }

    bindData() {
        const anotherList: any[] = [
            this.toppingList[0],
            this.toppingList[1]
        ]

        this.toppings.setValue(anotherList)
    }
}