Angular Material Mat-根据最长选项宽度选择宽度

问题描述 投票:0回答:4

我有一个带有选项的垫选择,我希望将其内联设置为文本,并且下拉列表的长度与最长的选项一样长。我可能可以使用 js / css vanilla 风格进行一些黑客攻击,但正在寻找更好的解决方案。有什么想法吗?

<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>
css angular sass width angular-material2
4个回答
11
投票

请尝试这个(对于所选选项)...

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

1
投票

对于

"@angular/material": "13.3.2"
这对我有用

  ::ng-deep .mat-select-value {
    max-width: 100%;
    min-width: 100%;
    width: auto;
  }
  ::ng-deep .mat-form-field-infix {
    width: auto !important;
    min-width: 180px !important;
    padding-right: 13px !important;
  }

0
投票

使用

panelClass
的 Angular Material v17 解决方案。

   <mat-select panelClass="custom-class">

为了匹配

mat-select
的宽度,Angular-material 在
.cdk-overlay-panel
元素的 style 属性中设置宽度。 Angular-material 还将面板类放在
.cdk-overlay-panel
的子元素上,因此需要
:has(>...)
!important
来覆盖面板宽度。

.cdk-overlay-pane:has(>.custom-class){
   width: initial !impontant;
}

我的具体用例只需要尺寸变大,所以我使用:

.cdk-overlay-pane:has(>.custom-class){
   min-width: fit-content;
}

-4
投票

尝试这个代码,它可以工作,但它不是动态的。

::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;
}
© www.soinside.com 2019 - 2024. All rights reserved.