【问题标题】:How can I not show the selected on dropdown of mat-select如何在 mat-select 的下拉列表中不显示所选内容
【发布时间】:2021-09-06 02:50:53
【问题描述】:

我正在尝试使用 mat-select 作为弹出菜单,效果很好,我面临的问题是 mat-select 默认情况下通过显示不同的背景来显示用户之前选择的内容。如果您将它用作值框,这可能没问题,但是当您将其用作菜单时,它就不是那么好了。 所以我的问题是我必须修改哪些值/样式才能使之前选择的项目看起来与其他所有项目相同。

我在 Stackblitz Sample附上了一个样本

这就是我所说的之前选择 Taco 的效果

【问题讨论】:

  • 有点苛刻,但如果您需要精确控制样式,请不要使用 Angular Material..
  • 您可以使用::ng-deep来更改角材质提供的默认样式。

标签: angular angular-material


【解决方案1】:

首先,这种样式由mat-selectedmat-active 类应用于选定的mat-option

我尝试使用 TypeScript 删除这些选定的 mat-option 类。

这是我想出的解决方案:

我在mat-select 上创建了一个子视图,并在mat-select 上创建了一个(click) 函数。然后,每当用户单击 mat-select 时,我都会遍历其所有子 mat-option 并从每个类中删除 mat-selectedmat-active

以下是我所做的更改:

HTML 文件:

<mat-select [(ngModel)]="selectedValue" name="food" #matOption (click)="removeSelectedClass($event)">
    <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
    </mat-option>
</mat-select>

TypeScript 文件:

export class SelectFormExample {
    @ViewChildren('matOption') matOptions: QueryList<any>;
    
    removeSelectedClass(event: any) {
        this.matOptions.first.options._results.forEach((elem: any) => {
            elem._element.nativeElement.classList.remove('mat-selected', 'mat-active');
    });
}

您可以通过 fork 示例代码 here 找到开发的示例解决方案

我希望这会有所帮助。请让我知道从选定的 viewchild 中删除类的更好方法。

【讨论】:

    【解决方案2】:

    您可以通过以下方式覆盖您的样式:

    .mat-select-panel .mat-option.mat-selected:not(.mat-option-multiple) 
    {
      background: unset;
    }
    .mat-primary .mat-option.mat-selected:not(.mat-option-disabled) {
      color: unset;
    }
    .mat-option:hover:not(.mat-option-disabled), .mat-option:focus:not(.mat-option-disabled) {
      background: *your hovered option style* !important;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 2013-11-12
      相关资源
      最近更新 更多