Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Mat-Select Width Based on Longest Option Width

I have a mat-select with options, I am looking to set this inline to text and have the drop down only be as long as the longest option. I can probably do some hackery with js / css vanilla style, but looking for a better solution. any thoughts?

<mat-select
  [ngClass]="{'missing-selection': !SelectedOption}"
    [(value)]="SelectedOption"
    id="select"
    (selectionChange)="optionChange($event)"
  >
    <mat-option
      *ngFor="let option of data.Options"
      [value]="option.Value"
      >{{ option.Label}}</mat-option
    >
  </mat-select>
like image 912
Jared Kremer Avatar asked Feb 04 '19 14:02

Jared Kremer


1 Answers

Please, try this (for selected option)...

.auto-width{
    .mat-form-field {
        width: auto !important;
    }
    .mat-select-value {
        max-width: 100%;
        width: auto;
    }  
}

<div class="auto-width">
    <mat-form-field>
      <mat-select>
        <mat-option value="long">Long description</mat-option>
        <mat-option value="foo">Foo</mat-option>      
      </mat-select>
    </mat-form-field>
</div>
like image 140
João Portella Avatar answered Nov 15 '22 23:11

João Portella