Is it possible to indicate which mat-tab has been clicked? Especially when the mat-tabs are being generated dynamically

In my UI, I have a dynamic display of mat-tabs that change in number and data based on values from the backend. These tabs are generated dynamically, and when one is clicked, an ID is passed to a function for processing. I want to be able to identify the specific mat-tab that has been clicked and keep it highlighted until the user navigates to another page.

I attempted to use

mat-tab:active{background-color: #333}
, but it did not work as expected.

    <mat-tab-group [selectedIndex]="Index" (selectedTabChange)="tabChanged($event)" style="width:100%" #Tabgroup>
          <div *ngFor="let item of items; let last = last;" class="button">
            <mat-tab>
              <ng-template mat-tab-label>
                <span class="XYZ" id="item.Id"
                  (click)="setmodule(item.Id)">{{item.Name}}</span>
              </ng-template>
            </mat-tab>
          </div>
    </mat-tab-group>

No error messages were displayed, but the desired outcome was not achieved.

Answer №1

To ensure proper functionality, it is important to store the clicked tab ID in a variable and then utilize ngClass in this manner:

<mat-tab-group [selectedIndex]="Index" (selectedTabChange)="tabChanged($event)" style="width:100%" #Tabgroup>
      <div *ngFor="let item of items; let last = last;" class="button">
        <mat-tab [ngClass]="{'tab-selected': selectedTabId==item.id}">
          <ng-template mat-tab-label>
            <span class="XYZ" id="item.Id"
              (click)="setmodule(item.Id)">{{item.Name}}</span>
          </ng-template>
        </mat-tab>
      </div>
</mat-tab-group>

When defining your styles, remember to include the following:

.tab-selected
{
  background-color: #333;
  // Additional styles can be added here
}

Answer №2

To change the background color of an active tab, you can target the "mat-tab-label-active" class. This class is automatically applied when a tab is active.

You can modify this class using ng-deep as shown below:

::ng-deep .mat-tab-label-active {
  background-color: #333;
}

If you have multiple components with mat-tabs and want to style them individually, you can assign a class to your mat-tab-group element like so:

<mat-tab-group class="menu-tab" [(selectedIndex)]="selectedTabIndex">
  <div *ngFor="let item of menuList">
  <mat-tab>
    <ng-template mat-tab-label>
      <a class="side-nav-link">{{ item.value}}</a>
    </ng-template>
  </mat-tab>
</div>
</mat-tab-group>

To style the active tab within the specific tab group, use the following CSS:

.menu-tab ::ng-deep .mat-tab-label-active {
  background-color: #333;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Sorry, but sessionStorage is not functioning correctly

So I created an input called "textmoney" that calculates the user's potential yearly earnings. Upon pressing enter, a link appears directing to another page with a more accurate estimation of the initial answer. I wanted to store and retrieve the "tex ...

The grayscale effect is not functioning on the default web browser of an Android device

I have implemented a grayscale effect for an image using the following CSS code snippet: img.grayscale { filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\&apo ...

What is the best way to add an Angular directive to ever-changing HTML content?

When creating dynamic HTML content, I am using the mark tag to highlight text. Depending on a condition, I want to apply one of two styles. To specify a CSS class, I can do it this way: <mark class='selected'> However, when trying to use ...

Access the RxJS subscription data once and save it for later reuse

Currently, I am retrieving plans from a service using RxJS: public class PlansListComponent implements OnInit { private plans$: Subject<PlanDTO> = new BehaviorSubject([]); ngOnInit():void { this.serverService .list() .subscribe( ...

Dynamic visual content (map)

I'm currently working on creating an interactive image for my website where clicking on points A, B, C, ... N will reveal bubbles with images and text inside them. Would anyone be able to provide guidance on how to achieve this? Or direct me to resou ...

How can CSS be effectively handled across master pages, content pages, and user controls?

When working on a web project that includes content pages, master pages, and user controls, what are the best practices for writing CSS for each of these elements? Should it be included in the page itself, or in a separate file? Is it better to have a sepa ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Obtain an array containing only one property value from an array of objects

Within my array of objects, I am looking to extract all the controls and move them to a new array: this.formModel = { sections: [ { title: 'Section 01', controls: [ new FormControlInput({ ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

Centering an item using Bootstrap

I am using bootstrap in reactjs and attempting to center a text in the middle of the screen, but it seems to not be working. Can someone please point out what I am doing wrong? <div className="h-100 d-flex align-self-center justify-content-center&q ...

Issue encountered during Angular unit test execution

I encountered an issue while conducting unit testing in Angular. I am attempting to test the creation of a component. Please refer to the error below and help me understand why this problem is occurring. I have also imported the necessary services related ...

Designing table rows to resemble full-width cards

Looking for a way to transform the rows of a table into full-width cards while maintaining the row layout? Here's what I have tried so far: tbody>tr { display: block; padding: 1rem 0.5rem 1rem 0.5rem; margin: 1.5rem; border: 1px solid rgba( ...

Using Ionic 4 and Angular 7 to make straightforward remote HTTP requests with Cross-Origin Resource

I'm still navigating my way through ionic and angular, trying to understand how to send a basic HTTP request to a remote server without dealing with CORS. My initial attempt involved the following code snippet: this.httpClient.get<MyObj>("/api" ...

Select the <Tr> element effortlessly with a single click

<tr class="rowClass1" id="TR_parentof_form1:tableExIlacList:0:rowAction1" onclick="return(hX_6.runEvent(this, event));" style="cursor: pointer;"><td><span id="form1:tableExIlacList:0:rowAction1"> I am attempting to automatically trigger ...

The argument labeled as 'shop' does not fit the criteria for the parameter 'items' or 'cart'

I've been doing some research but haven't had any luck finding a solution. I'm fairly new to Angular and currently working on a webstore project. I followed a tutorial, but encountered an error along the way. import { select, Store } from & ...

Decoding JavaScript elements embedded in an HTML website

My current HTML site includes the following code: <script type="text/javascript"> jwplayer('player_container').setup( { 'width': '640', ...

Eliminate extraneous space with the clearfix:after pseudo-element

Could use some help figuring out how to remove the unwanted whitespace caused by clearing the float (specifically after the tabs). Any suggestions on how to fix this issue? Take a look at the code snippet below (jsfiddle): /* Clearfix */ .clearfix:af ...