简体   繁体   中英

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>

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>

Try this code, it works but it is not dynamic.

::ng-deep .mat-form-field {
  width: 50px !important;
}
::ng-deep .mat-label {
    width: 50px !important;
}
::ng-deep .mat-select {
    width: 50px !important;
}

::ng-deep .mat-option {
    width: 50px !important;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM