中没有足够的空间<mat-select>。如何添加多行<mat-option>?



我想在选项文本下有描述选项的附加行。 默认情况下,mat-select 限制字符数并添加"..."在行的末尾。我想要需要多行选项。 斯塔克闪电战演示:https://stackblitz.com/edit/angular-wj9svw 我的代码:

export class SelectOverviewExample {
foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak longDescription longDescription longDescription longDescription longDescription'},
{value: 'pizza-1', viewValue: 'Pizza longDescription longDescription longDescription longDescription longDescription longDescription v v longDescription'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
}

.html:

<mat-form-field>
<mat-select placeholder="Favorite food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
<b> some additional text text text text texttext </b>
</mat-option>
</mat-select>
</mat-form-field>

使用以下 css:

.mat-select-panel mat-option.mat-option {
height: unset;
}
.mat-option-text.mat-option-text {
white-space: normal;
}

/deep/ .mat-select-panel mat-option.mat-option {
height: unset;
}
/deep/ .mat-option-text.mat-option-text {
white-space: normal;
}

示例演示在这里 - https://stackblitz.com/edit/angular-material2-issue-ndtstg

.mat-option {
margin: 1rem 0;
overflow: visible;
line-height: initial;
word-wrap: break-word;
white-space: pre-wrap;
}
.mat-option i {
display: block;
font-size: 1.5rem;
opacity: 0.6;
margin-left: 0.5rem;
}

这也很有帮助

我通过编写一个MultiLineOptionDirective扩展<mat-option>并调用MatListItemMatGridTile@angular/material/core执行的相同setLines()函数来解决

<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select [formControl]="mySelect">
<mat-select-trigger>{{ mySelect.value }}</mat-select-trigger>
<mat-option *ngFor="let food of foods" [value]="food.value" multiLineOption>
<h4 mat-line>{{ food.value }}</h4>
<p mat-line>{{ food.description }}</p>
</mat-option>
</mat-select>
</mat-form-field>

https://stackblitz.com/edit/angular-material-multi-line-option

编辑:"extends"可能会被误解,扩展为在指令中扩展元素的功能,而不是类扩展基类的功能。

这将在 2 列中显示长文本。

在 .scss 中添加:(如果您希望每行具有相同的高度,您可以删除最后 3 行(

.multiline-mat-option.mat-option {
white-space: normal;
line-height: normal;
height: unset;
padding-top: 0.9em;
padding-bottom: 0.9em;
} 

在 HTML 中:

<mat-option class="multiline-mat-option"...

我最近遇到了这个问题,经过一些调试,我发现您可以引用与 关联的类。

.mat-option {
white-space: normal;
line-height: normal;
}

这会将文本换行到下一行并相应地调整高度。如果您正在使用动态数据,也可以执行line-height: auto

我使用了以下CSS。

::ng-deep .mat-select-panel mat-option.mat-option {
height: unset;
line-height: 1.2em;
padding-top: 0.9em;
padding-bottom: 0.9em;
}
::ng-deep .mat-option-text.mat-option-text {
white-space: normal;
}

这不再是 Angular Material 16 (MDC( 的问题,它现在根据其内容自动调整mat-option的高度。

最新更新