简体   繁体   English

如何自定义角度垫选项的选定选项的样式

[英]How to customise style of selected option for angular mat-option

I am working on an angular application using the angular material library.我正在使用角度材料库开发一个角度应用程序。

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>

On dropdown, the option works nicely as expected with each option having the option name and a coloured badge beside it.在下拉菜单中,该选项按预期工作得很好,每个选项都有选项名称和旁边的彩色徽章。 However, when the option is selected, the option is no longer styled inside the form control field. However, when the option is selected, the option is no longer styled inside the form control field.

In the inspected HTML, the selected field is shown as:在检查的 HTML 中,所选字段显示为:

<span class="mat-select-min-line ng-star-inserted">option-name option-label</span> 

not even respecting the original DOM structure of the option.甚至不尊重选项的原始 DOM 结构。

Is there a way to choose what shows up in the form control field after the option is selected (eg just showing option.name and not needing the label), or possibly style the selected field keeping the structure passed to the original mat-option ?有没有办法在选择选项后选择表单控制字段中显示的内容(例如仅显示 option.name 而不需要标签),或者可能设置所选字段的样式,保持结构传递给原始mat-option

Any help is appreciated since there seems to be no documentation on the <mat-option> component.感谢任何帮助,因为似乎没有关于<mat-option>组件的文档。

Work with <mat-select-trigger> element to customize the selected option text.使用<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>
  1. Create selectedOptionObj variable to store the selected option object.创建selectedOptionObj变量以存储选定的选项对象。
  2. With selectionChange event to trigger onSelectOption method for storing selected option object by selected value.使用selectionChange事件触发onSelectOption方法,用于通过选定值存储选定的选项对象。
selectedOptionObj: any;

onSelectOption(event: any) {
  let selectedValue = event.value;

  this.selectedOptionObj = this.options.find((x) => x.value == selectedValue);
}

Sample StackBlitz Demo 示例 StackBlitz 演示


Reference参考

Select with custom trigger text 使用自定义触发文本选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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