Search code examples
cssangularnavmat-tab

Angular/CSS onload how to get the default tab active


I am creating a angular page which uses mat-tab-nav-bar and mat-tab-link.

dashborad.component.html

<div><nav mat-tab-nav-bar>
    <a mat-tab-link [routerLink]="['/home']">Home</a>
    <a mat-tab-link [routerLink]="['/admin']">Admin</a>
    <a mat-tab-link [routerLink]="['/order']">Orders</a>
    </nav></div>
  <div><router-outlet></router-outlet></div>

AppRoutingModule

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { HomeComponent} from './components/home/home.component';
import { AdminComponent} from './components/admin/admin.component';
import { OrdersComponent} from './components/orders/orders.component';


const routes: Routes = [
  {path: 'dashboard', component: DashboardComponent ,
children: [
     {path: 'home', component: HomeComponent},
    {path: 'admin', component: AdminComponent},
    {path: 'order', component: OrdersComponent},
    {path: '', redirectTo: 'home', pathMatch: 'full'}
]
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I am able to get page as I want except one thing. When the page gets loaded it shows the default page but the tab is not showing as selected. When I click a tab it becomes active and shows the same page.So would like to know how to achieve the requirement.


Solution

  • You can use routerLinkActive attribute for the same. Where this attribute adds a class name to active element and then you can add CSS to that class

    Find the syntax:

    <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
    

    Css:

    .active-link
    {
    Color: Blue;
    Font-size: 17;
    }