ilya.chepurnoy
ilya.chepurnoy

Reputation: 515

Make Angular Material mat-select automatically take width of its selected option

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.

Upvotes: 3

Views: 8549

Answers (2)

NKFahrni
NKFahrni

Reputation: 41

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.

Upvotes: 0

ilya.chepurnoy
ilya.chepurnoy

Reputation: 515

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...
}

Playground with this fix

Upvotes: 3

Related Questions