Angular Material Select:如何自定义 .mat-select-panel 本身

新手上路,请多包涵

我使用Angular Material Select具有这种html结构

<mat-form-field class="year-drpdwn-vacay-stock">
    <mat-select placeholder="Year">
        <mat-option>None</mat-option>
        <mat-option *ngFor="let yr of year"  [value]="yr">{{yr}}</mat-option>
    </mat-select>
</mat-form-field>

我放置了一个类,因为我也在其他组件中使用了 Select。我尝试添加

::ng-deep .mat-select-panel {
    margin-top: 20%;
}

在 CSS 中自定义,但问题是,包含另一个选择框的其他组件也会受到影响(继承 margin-top CSS)

目前我有这个 CSS

 .year-drpdwn-vacay-stock mat-select.mat-select :host ::ng-deep .mat-select-panel {
    margin-top: 20%;
}

但它仍然不起作用。

更新

目标:我希望选项面板在打开选择框时稍微向下移动,这就是为什么我希望 .mat-select-panel 的上边距为 20%

原文由 Char 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

使用 cdk-overlay-container 作为基础并像这样转到选项窗格,mat-select 使用绝对位置,其中没有任何子项。所以你需要将你的风格应用到 cdk-overlay-container

 .cdk-overlay-container .cdk-overlay-pane{
   margin-top: 7%;
}

这是 演示

编辑:

好的,所以您与可以添加的其他元素存在冲突问题

panelClass="testClass"

<mat-select placeholder="Favorite food" panelClass="testClass">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>

像这样改变你的班级

.cdk-overlay-container .cdk-overlay-pane .testClass{
margin-top: 7%;
}

演示

原文由 Just code 发布,翻译遵循 CC BY-SA 4.0 许可协议

  1. 如果你直接在styles.css (root) 中使用!important 标记将样式应用到类,它会覆盖任何其他样式。但是你会通过这样做来打破封装。
  2. 如果您使用 /deep/ 在组件中应用样式,则样式将被覆盖,mat-form-field /deep/ (class-name) {}(已弃用的问题)请阅读 https://blog.angular-university.io/ angular-host-context/ 进行深入解释
  3. 由于 Deprecating 问题,您实际上可以尝试使用 vanilla javascript 添加/删除类,但直接操作 dom 是一种不好的做法。

总结:使用Deprecated语法不好,在root级别应用样式会导致封装问题,直接操作dom是不好的做法,因此可以使用angular提供的工具操作dom来解决上述问题,请参考以下链接学习关于以角度操作 dom 的最佳实践 https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02

原文由 Akshay Rajput 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题