我想在选项文本下添加描述该选项的行。 默认情况下,mat-select 限制字符数并在行末尾添加“...”。我想要有需要的多行选项。 stakckblitz 演示: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>
并调用 setLines()
和 MatListItem
从 MatGridTile
执行的相同
@angular/material/core
函数
<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
编辑:“扩展”可能会被误解,指令中的扩展扩展了元素的功能,而不是类扩展了基类。
这显示了 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
的高度。