Guide to configuring the active Tab in Angular 6 using Angular Material Design

I've searched high and low for a solution to this issue, but I haven't been able to find one.

In a particular component, I have a material tab control. However, the active tab doesn't display until I click on one of the tabs on the page.

app.component.html

<nav mat-tab-nav-bar  mat-align-tabs="center" mat-stretch-tabs >
  <a  mat-tab-link *ngFor="let link of NavigateTo" [routerLink]="link.path" routerLinkActive #rla="routerLinkActive"
    [active]="rla.isActive">
    {{link.label}}
  </a>
</nav>
<router-outlet></router-outlet>

app.component.ts

 NavigateTo : Array<object> = [
                         {label:'Employee Master',path:'EmployeeMaster',index:0},
                         {label:'Table Master',path:'TableMaster',index:1}
                        ];

Answer №1

Unfortunately, it's quite challenging for me to actively troubleshoot the issue without being able to replicate it on stackblitz. However, here is my theory:

<nav mat-tab-nav-bar  mat-align-tabs="center" mat-stretch-tabs >
  <a  mat-tab-link *ngFor="let link of NavigateTo" [routerLink]="link.path" (click)="activeLinkIndex = link.index" routerLinkActive #rla="routerLinkActive"
    [active]="activeLinkIndex===link.index">
    {{link.label}}
  </a>
</nav>
<router-outlet></router-outlet>

Below are the suggested modifications for the component. I've provided pseudo code, but the essence is to assign your route parameters to the corresponding index in NavigateTo. Additionally, consider adding / to your link paths:

activeLinkIndex = 0;

.
.
//this.activeLinkIndex = 
// map the current route parameter to this.NavigateTo and get the desired route index
 .
 .
NavigateTo : Array<object> = [
  {label:'Employee Master',path:'/EmployeeMaster',index:0},
  {label:'Table Master',path:'/TableMaster',index:1}
];

Answer №2

It seems that you are not on any of the specified routes in the second code snippet.

You have two options:

  • Redirect all routes to one of your specified paths:

    import { Route } from '@angular/router';
    // ...
    export const AppRoutes: Route[] = [
      { path: '**', redirectTo: '/<your-path>' }
    ]
    
  • Or set the initial route to redirect to:

    import { Route } from '@angular/router';
    // ...
    export const AppRoutes: Route[] = [
      { path: '', pathMatch: 'full', redirectTo: '/<your-path>' }
    ]
    

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

Why am I receiving a peculiar type error with @types/jsonwebtoken version 7.2.1?

My current setup includes node v6.10.3, typescript v2.3.4, and jsonwebtoken v7.4.1. Everything was running smoothly until I decided to upgrade from @types/jsonwebtoken v7.2.0 to @types/jsonwebtoken v7.2.1. However, after this update, an error started poppi ...

Oops! There was an unexpected error in the authGuard: [object Object] was not caught as expected

I've been working on implementing authGuard in my app, but I keep encountering an error. Below is the guard implementation: canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { /** * Returning an observable of type boolea ...

Encountering an Angular error while trying to use the command "npm run dev:ssr" to observe server-side rendering on the localhost

When I run this command, it starts listening on port 4200 but the page keeps loading without ever fully loading and shows this error in the command prompt: Unhandled Promise rejection: connect ECONNREFUSED 127.0.0.1:6379 ; Zone: <root> ; Task: Promis ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

What are the steps to validate a form control in Angular 13?

My Angular 13 application has a reactive form set up as follows: I am trying to validate this form using the following approach: However, I encountered the following error messages: Additionally, it is important to note that within the component, there ...

Observable subscription results in a return of undefined

My observable is being filled with data from the backend using a service. The backend is providing the correct data, but I am having trouble building a pie chart with the values from the observable. The relevant part of the code is as follows: this.dataSe ...

How can I display an agm-polyline within a map in Angular 7?

I need assistance with adjusting the polylines on my map and dynamically setting the zoom level based on their size and position. Here is the code I am currently using: <agm-map style="height: 500px" [latitude]='selectedLatitude' [longitude ...

The connection to Firebase is being refused when attempting to use the http.post method in Ionic

In my Ionic 3 Angular app deployed on Firebase static hosting, the problematic section of code appears as follows: var data = {"message" : time, "user_id" : user}; return new Promise((resolve, reject) => { ...

Utilizing the Next.js "Link" Element as a Personalized React Component Using Typescript

When attempting to utilize the "Link" element as a custom react component that I modified with typescript to enhance its functionality, I encountered a recurring issue in my project. Each time I used it, I had to include a property named props which contai ...

Is there a way to halt the automatic expansion of a mat-expansion-panel upon being clicked?

I have a specific requirement for managing the opening and closing of my mat-expansion-panel. In my implementation, I want to rely solely on the panel's [expanded] input property to control its state. To achieve this, I am using NGRX as my state manag ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Filtering incoming data from a Firestore database: A step-by-step guide

I'm facing a challenge while trying to incorporate this filtering mechanism into my code. FILTERING An issue arises when I attempt to implement the following lines of code: function search(text: string, pipe: PipeTransform): Country[] { return CO ...

I am currently working on a project using the most up-to-date version of Angular, and I encountered an issue where the property 'value' is not recognized on the type 'EventTarget'

When utilizing the $event with the onkeyup event and attempting to pass the input field's value to the filter Function, it is not functioning as expected. <div class="container mx-auto p-5"> <div class="searchBar"> ...

Exploring Angular 2's Routing Features Across Different Cultures

Looking to integrate culture into all routes in my application utilizing RC4. How can I adjust the existing routes to achieve this objective? export const routes: RouterConfig = [ ...ItemRoutes, ...LibraryRoutes, { path: '', redirectTo: 'd ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Unable to determine all parameters for MatProgressSpinner

I am trying to incorporate Angular Material's Progress spinner component into my project. However, I am facing an issue when importing the module. import {MatProgressSpinnerModule} from '@angular/material'; The error message displayed in t ...

Deploying AngularApp with Cordova on iOS results in a blank screen

Encountering a White Screen Issue on iOS While Trying to Load an Angular App with Cordova. After modifying the base href to "./" in my Angular app project, it runs smoothly on all platforms except for iOS. Any ideas why it's not loading properly on iO ...

Pressing the enter key on a table column in Angular will trigger an automatic button click

In my Angular 9 application, I have a dynamic table in the HTML with editable columns. When I edit a value and press ENTER, it triggers a click event associated with a button in another column instead of applying the edit. How can I prevent this unexpected ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...