如何更改Angular Material选项的样式?

3
我使用以下代码:
::ng-deep{
 .mat-select-panel{
   border-radius: 10px;
   border: 1px solid gray;
   position:absolute;
   top: 50px;
 }
}

我原本预期它应该是这个样子:

enter image description here

但实际上,它现在是这个样子:

enter image description here

而且,从所选的位置打开它很难看:

enter image description here


你有没有看过我分享的最新演示? - Adrita Sharma
3个回答

5

我只是将panelClass添加到选择标签中,并在styles.scss中为该类设置样式。

Html:

<mat-form-field>
  <mat-select disableOptionCentering panelClass="dropDown-seasons-panel">
      <mat-option *ngFor="let season of seasons" [value]="season.value">
         {{season.viewValue}}
      </mat-option>
  </mat-select>
 </mat-form-field>

styles.scss:

.dropDown-seasons-panel {
  border-radius: 10px !important;
  border: 1px solid gray !important;
  position: absolute !important;
  top: 50px !important;
}

我想在mat-select中显示边框半径而不是在mat-options中,我该如何实现? - Optimist Rohit
你可以为这个类设置样式:".mat-select-panel" - heliya rb
有一个更好的解决方案,不使用!important。请查看此链接,第3条“在单独的全局样式中覆盖AM样式 - 不作用域!”https://betterprogramming.pub/best-way-to-overwrite-angular-materials-styles-e38dc8b84962 - plutownium

3

请确认,您正在使用CSS还是SCSS。如果您正在使用CSS,则无法正常工作。请更改为SCSS。

我已经在mat-select组件中使用panelClass属性添加了类。通过使用该类,您可以更新CSS

如果您正在使用SCSS,请参阅我的演示- https://stackblitz.com/edit/angular-jhxdfy-piucvw

同时检查您的全局样式CSS文件。可能该CSS会覆盖此CSS。


我使用scss。我完全按照你的演示做,但是什么都没有发生,但是如果我将这段代码添加到style.scss中,一切都正常,但这不是解决办法,因为它会改变我整个项目的样式。 - heliya rb
你能添加你的HTML部分吗?然后我可以提供建议。 - Jeba
<div class="seasons-part"> <span>Season Name:</span> <mat-form-field> <mat-select disableOptionCentering md-container-class="mySelect"> <mat-option *ngFor="let food of foods" [value]="food.value"> {{food.viewValue}} </mat-option> </mat-select> </mat-form-field> </div> - heliya rb
另外,我查看了styles.scss文件,没有任何覆盖的类。 - heliya rb
1
我刚刚更新了链接(https://stackblitz.com/edit/angular-jhxdfy-piucvw),我使用mat-select组件的panelClass属性添加了一个类。通过使用该类,您可以更新CSS。 - Jeba
非常感谢你的帮助。你的演示对我来说不起作用,但是我给选择标签添加了panelClass,并在styles.css中使用了这个类,最终一切都正常工作了。真的非常感谢你的帮助。 - heliya rb

1
这可能不是最佳实践,但你可以尝试在style.css中使用!important来添加它们。
.html
<mat-select id='myCustomDropdown' placeholder="Favorite food">
    <div class="custom-style">
        <mat-option *ngFor="let food of foods" [value]="food.value">
            {{ food.viewValue }}
        </mat-option>
    </div>
</mat-select>

style.css

.custom-style .mat-option{
    color:red !important
 }

工作演示

(保留HTML)

可以的,你可以用class为custom-panel的div包裹起来,然后使用选择器custom-panel.mat-select-panel。 - Adrita Sharma
请你能否为我演示一下? - heliya rb
请查看工作演示,在style.css中,我添加了#myCustomDropdown .mat-select-placeholder{ color:red !important } - Adrita Sharma
我的选择标签没问题,但是选项标签不起作用。 - heliya rb
请问您能否演示一下如何更改选项的样式? - heliya rb
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接