【问题标题】:Angular Material Select: How to customize .mat-select-panel itselfAngular Material Select:如何自定义 .mat-select-panel 本身
【发布时间】:2019-05-10 23:28:09
【问题描述】:

我有这种使用 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%

【问题讨论】:

  • 你能告诉我们你真正想要做什么吗?
  • @Justcode 我希望 mat-select-panel 在打开选择框时移动一点。感谢你的提问。我会更新我的问题

标签: css angular angular-material material-design angular-material2


【解决方案1】:
  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

【讨论】:

  • 谢谢,但目前还没有替代品stackoverflow.com/questions/47024236/…
  • 我猜是因为封装样式不会出现在组件之外,在组件内部使用下面的 CSS。 (你在哪里使用元素)/deep/ .mat-select-panel { margin-top: 20%; }
  • @Akshay,您是否尝试使用 :host ::ng-deep .mat-select-panel { ... } 和 :host 这限制了当前组件。
【解决方案2】:

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

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

这里是demo

编辑:

好的,你可以添加的其他元素有冲突问题

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%;
}

demo

【讨论】:

  • 还需要'disableOptionCentering',否则框会向上移动
【解决方案3】:

要在打开选择框时向下移动选项面板,请使用如下所示的“disableOptionCentering”属性,这对我有用。

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

【讨论】:

  • 这是在底部显示下拉菜单的最简单方法。感谢分享。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2019-03-20
  • 2019-10-25
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多