How do I make automatically take width according to its selected option's width? I've looked through the API of mat-select, and was not able to find an option/input for this.
            Asked
            
        
        
            Active
            
        
            Viewed 3,570 times
        
    2 Answers
2
            
            
        Just sharing a solution to the problem. Here's how (turn ViewEncapsulation off or prepend these selectors with ::ng-deep):
.mat-select-value {
  max-width: max-content !important; // <= SOLUTION HERE...
}
.mat-form-field-infix {
  width: fit-content !important;  // <= and HERE...
}
        ilya.chepurnoy
        
- 332
 - 4
 - 9
 
0
            
            
        My Solution is something mixed with this answer.
I took his code and modified it a bit, then in my Angular App I put the class into the styles.scss (This will be the outer most scss/css file you can find). And it works without ::ng-deep
This is my solution:
.mat-form-field-infix { 
   width: fit-content !important;
   min-width: 200px !important; 
}
This solution is not very flexible though, thats why I would suggest you calculate the width in your script and set the elements width to that. it would look something like this:
HTML:
<mat-form-field [style.width.px]="setSizeOfDropDown(16)">
Typescript:
setSizeOfDropDown(fontSize:number):number{
let width: number = minWidth; //This is so that we dont have any codesmells
return fontSize * myOptionsArr.reduce((a,b)=>{
    a.length>b.length?a:b; //I used the shorthand if because it looks very clean
}).length
I multiplied the fontSize with the length of the longest string in the Array. and that is my Select width.
        NKFahrni
        
- 11
 - 1