Angular Material: mat-select not selecting default

后端 未结 17 1450
不思量自难忘°
不思量自难忘° 2020-11-28 23:18

I have a mat-select where the options are all objects defined in an array. I am trying to set the value to default to one of the options, however it is being left selected

17条回答
  •  不知归路
    2020-11-28 23:56

    A comparison between a number and a string use to be false, so, cast you selected value to a string within ngOnInit and it will work.

    I had same issue, I filled the mat-select with an enum, using

    Object.keys(MyAwesomeEnum).filter(k => !isNaN(Number(k)));
    

    and I had the enum value I wanted to select...

    I spent few hours struggling my mind trying to identify why it wasn't working. And I did it just after rendering all the variables being used in the mat-select, the keys collection and the selected... if you have ["0","1","2"] and you want to select 1 (which is a number) 1=="1" is false and because of that nothing is selected.

    so, the solution is to cast you selected value to a string within ngOnInit and it will work.

提交回复
热议问题