Angular Material Mat-Select Width Based on Longest Option Width

16,724

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>
Share:
16,724
Jared Kremer
Author by

Jared Kremer

Updated on June 03, 2022

Comments

  • Jared Kremer
    Jared Kremer almost 2 years

    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>
    
  • SamYonnou
    SamYonnou over 4 years
    @nicolas.leblanc i got it working by adding ::ng-deep to the outer selector
  • Ollie
    Ollie over 4 years
    It does not look great though... the dropdown arrow is all the on the left when no value is selected, and just to the right of the text when one is selected (not in the far right). When a long description is selected, all the text is visible, but the line along the bottom of the control does not extend to match it.
  • Paul-E
    Paul-E almost 3 years
    May be I'm late to the party, but, it might help someone, replace width:auto with min-width: 100%, that moves the dropdown arrow to the right side. .mat-select-value { max-width: 100%; min-width: 100%; }