簡體   English   中英

如何使用 CSS 設置 Angular 材質標簽的樣式?

[英]How do I use CSS to style Angular Material tabs?

我對 Angular 很陌生。 我最近在我的應用項目中添加了 Angular 材料選項卡,類似於下面的一個。

<mat-tab-group>
  <mat-tab label="First"  class="firstTab"> Content 1 </mat-tab>
  <mat-tab label="Second" class="secondTab"> Content 2 </mat-tab>
  <mat-tab label="Third"  class="thirdTab"> Content 3 </mat-tab>
</mat-tab-group>

在我的應用程序中,有時我需要將某些選項卡引起用戶的注意。 我正在考慮的方法是通過賦予以下特性來突出顯示感興趣的選項卡:

.highLightTab{
   border-width: 9px;
   border-style: solid;
   border-color: orange;
}

在此處輸入圖像描述

實現上述目標的傳統方法是通過

$(".secondTab").addClass("highLightTab");

然而,事實證明這是不可能實現的,因為我無法為運行時生成的任何 Mat-X 元素定制 CSS 類/CSS 樣式。

誰能告訴我如何實現這一目標?

要將自定義 class 添加到材質選項卡,您必須使用ng-template語法:

<mat-tab-group>
    <mat-tab>
        <ng-template mat-tab-label>
            <span class="my-custom-class">Security</span>
        </ng-template>
        Content 1
    </mat-tab>
    <mat-tab label="Second" class="secondTab"> Content 2 </mat-tab>
    <mat-tab class="my-custom-class" label="Third" class="thirdTab"> Content 3 </mat-tab>
</mat-tab-group>

有了這個,您可以像往常一樣my-custom-class樣式:

.my-custom-class {
  border-width: 9px;
  border-style: solid;
  border-color: red;
}

您還可以使用::ng-deep偽元素設置默認材質類的樣式。

:host ::ng-deep .mat-tab-label-active {
    border-width: 9px;
    border-style: solid;
    border-color: orange;
  }

:host是可選的,它將 styles 的范圍限定為當前組件中的選項卡。

附件是stackblitz演示。

我不推薦使用 ng-deep,因為它已被棄用:

https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep

相反,您應該將其設置為 angular 材料文檔:

https://material.angular.io/guide/theming

由於您可能會有很多自定義 styles 用於您的材料組件,因此這是一種更好的方法,您可以根據需要將所有材料自定義 styles 集中在一個 scss 文件中。

實現示例(未經測試,但應該可以):

我的自定義元素.scss

@import '~@angular/material/theming';

@mixin custom-tabs-theme() {
  .mat-tab-label-active  {
    border-width: 9px;
    border-style: solid;
    border-color: orange;
  }
}

全球材料主題.scss

@import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

@import './material/my-custom-elements.scss';

@include custom-tabs-theme();

angular.json

...
"styles": ["src/styles.scss", "src/app/global-material-theme.scss"]
...

注意:您可以通過這種方式編輯任何材料 css class。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM