[英]How to customise style of selected option for angular mat-option
我正在使用角度材料库开发一个角度应用程序。
component.html
<mat-select>
<mat-option *ngFor="let option of options" [value]="option.value">
<span> {{ option.name }} </span>
<span class="colorful-badge-class"> {{ option.label }} </span>
</mat-option>
</mat-select>
在下拉菜单中,该选项按预期工作得很好,每个选项都有选项名称和旁边的彩色徽章。 However, when the option is selected, the option is no longer styled inside the form control field.
在检查的 HTML 中,所选字段显示为:
<span class="mat-select-min-line ng-star-inserted">option-name option-label</span>
甚至不尊重选项的原始 DOM 结构。
有没有办法在选择选项后选择表单控制字段中显示的内容(例如仅显示 option.name 而不需要标签),或者可能设置所选字段的样式,保持结构传递给原始mat-option
?
感谢任何帮助,因为似乎没有关于<mat-option>
组件的文档。
使用<mat-select-trigger>
元素来自定义选定的选项文本。
<mat-select
[formControl]="selectedOption"
(selectionChange)="onSelectOption($event)"
>
<mat-select-trigger>
<span class="red" *ngIf="selectedOptionObj">
{{ selectedOptionObj.name }}
</span>
</mat-select-trigger>
<mat-option *ngFor="let option of options" [value]="option.value">
<span> {{ option.name }} </span>
<span class="colorful-badge-class"> {{ option.label }} </span>
</mat-option>
</mat-select>
selectedOptionObj
变量以存储选定的选项对象。selectionChange
事件触发onSelectOption
方法,用于通过选定值存储选定的选项对象。selectedOptionObj: any;
onSelectOption(event: any) {
let selectedValue = event.value;
this.selectedOptionObj = this.options.find((x) => x.value == selectedValue);
}
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.