Angular Material 2 unable to set default active tab

2.2k views Asked by At

Below code is taken from material.angular.io:

<nav mat-tab-nav-bar>
  <a mat-tab-link
     *ngFor="let link of navLinks"
     [routerLink]="link.path"
     routerLinkActive #rla="routerLinkActive"
     [active]="rla.isActive">
    {{link.label}}
  </a>
</nav>

<router-outlet></router-outlet>

component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  navLinks = [
    {label: 'Home', path: 'home'},
    {label: 'Contacts', path: 'contacts'},
    {label: 'Settings', path: 'settings'}
  ];
}

When i tried to run this sample, the nav requires clicking on home for the component to be opened. I want the contents of home to be displayed initially. How do you set the first value as the default active tab?

1

There are 1 answers

0
Teddy Sterne On BEST ANSWER

This is because the router is most likely at the root route /. If you want the home route to be the root route you need to set your router config for this to be the case or set the default to be the home route.

RouterModule.forRoot([{
  path: '',
  component: AppComponent,
  children: [{
    path: 'home',
    component: HomeComponent,
  }],
}, {
  path: '**',
  redirectTo: '/home',
}]);

In your current setup when you click the Home tab the router is navigating the page to /home.