不能在没有 ::ng-deep 和 !important 的情况下设置 mat-tab 样式

Cannot style mat-tab without ::ng-deep and !important

我有一些组件使用 HTML 中的 mat-tab 元素。当尝试在 CSS 中设置这些元素的样式时,我只能使用 ::ng-deep .mat-tab-label {} 设置它们的样式,并将 !important 放在至少一个样式更改旁边。我不想在应用程序中长期保留它,尤其是在阅读 this 文章之后。

以下是它如何分解开发人员工具中的元素:

<mat-card class="mat-card">
  <mat-tab-group class="mat-tab-group mat-primary">
    <mat-tab-header class="mat-tab-header">
      <div class="mat-tab-header-pagination mat-tab-header-pagination-before mat-elevation-z4 mat-ripple mat-tab-header-pagination-disabled>
      <div class="mat-tab-label-container">
        <div class="mat-tab-list">
          <div class="mat-tab-labels">
            <div class="mat-tab-label mat-ripple mat-tab-label-active ng-star-inserted">
            <mat-ink-bar class="mat-ink-bar">

如何在不使用 CSS 中的 ::ng-deep!important 的情况下设置这些元素的样式?

What can I do in order to style these elements without using ::ng-deep and !important in the CSS?

在这种情况下,您可以做的解决方案是使用 选择器特异性,然后将您的样式放在根样式中 /src/styles.css (注意:不要将它放在组件 styleUrls 中,您的样式将不起作用)

/* label style */
.mat-tab-label{
  background: green;
  color:white;
}
/* focus style */
.mat-tab-group.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus, .mat-tab-group.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus{
  background: red;
}
/* ink bar style */
.mat-tab-group.mat-primary .mat-ink-bar, .mat-tab-nav-bar.mat-primary .mat-ink-bar{
  background: yellow;
  height: 10px;
} 

要查看实时示例代码,请参阅此 link - https://stackblitz.com/edit/dmgrave-ng-so-anser-tabs-style?file=styles.css

希望对您有所帮助。