angularangular-materialscss-mixinsmat-tab

Angular change the background colour of the active mat-tab from code


Good morning, I have an Angular page that contains tabs made with Mat Tab. I managed to set the background colour of the active tab via scss with the following code and everything works correctly:

::ng-deep .mat-tab-label.mat-tab-label-active {
background-color: var(--user-main-color);
font-weight: 900;}

But now I would like to customise the colour dynamically, taking it via a REST call to the backend where the colour configuration is set. how can i do this? I thought of using [style.background-colour]="variable-name" but I don't understand how it can be done only for the active tab. thank you very much


Solution

  • try this:

    ::ng-deep .mdc-tab.mdc-tab--active{
      background-color: green !important;
      font-weight: 900;
    }
    

    UPDATE:

    if you want change styles in typescript try this:

    ts:

    ngAfterViewInit(): void {
        this.changeBackgroundColor();
        
      }
      changeActiveTab(): void {
        this.removePreviousActiveTabClass();
        this.changeBackgroundColor();
      }
    
      changeBackgroundColor(): void {
        const activeTab = document.getElementsByClassName('mdc-tab--active')[0];    
        (activeTab as HTMLElement).style.backgroundColor = 'red';
        (activeTab as HTMLElement).classList.add('active-tab');
      }
    
      removePreviousActiveTabClass(): void {
        const previousActiveTab = document.getElementsByClassName('active-tab')[0];
        (previousActiveTab as HTMLElement).style.backgroundColor = 'unset';
        previousActiveTab.classList.remove('active-tab');
      }
    

    in HTML file:

    <mat-tab-group (selectedIndexChange)="changeActiveTab()">
       <mat-tab label="First"> Content 1 </mat-tab>
       <mat-tab label="Second"> Content 2 </mat-tab>
       <mat-tab label="Third"> Content 3 </mat-tab>
    </mat-tab-group>
    

    in angular material 15 and later this code should work. in previous versions i think you have to replace (mdc-tab--active) class with your classes.