angularvmware-clarity

Set correctly active tab when open specific URL manually in Angular


I use Angular and Clarity. I have a navigation bar in app.component.html

<nav class="subnav">
    <ul class="nav">
      <li class="nav-item">
        <a class="nav-link" [ngClass]="{'active': activeTab === 'home'}" (click)="onSelectTab('home')" >HOME</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" [ngClass]="{'active': activeTab === 'contact'}" (click)="onSelectTab('contact')">CONTACT</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" [ngClass]="{'active': activeTab === 'help'}" (click)="onSelectTab('help')" >HELP</a>
      </li>
    </ul>
  </nav>

Snippets from app.component.ts

export class AppComponent implements OnInit{
  activeTab = 'home';

  constructor(private router: Router) {
  }

  onSelectTab(newTab: string): void {
    this.activeTab = newTab;
    this.router.navigate([newTab]);
  }
  ...
}

and the routes

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'help', loadChildren: () => import('./help/help.module').then(m => m.HelpModule) },
  { path: '', redirectTo: 'home', pathMatch: 'full'},
  { path: '**', redirectTo: 'home', pathMatch: 'full'}
];

It looks like this

enter image description here

If I click on contact or help everything will be ok. The corresponding tab and the component will be displayed and the new url will appear in the address bar.

The problem is that if I manually open not localhost:4200 but localhost:4200/help or localhost:4200/contact at the beginning then the corresponding component will show up. But the active tab will still be the home.

enter image description here

How can I set correctly active tab at the beginning if I manually open localhost:4200/help or localhost:4200/contact urls ?


Solution

  • Instead of calling the function selectTab each time you make a click to the link you could make use of RouterLink. Then with the attribute routerLinkActive you can automatically assign a class when the link desired is active.

    It would like this,

      <li class="nav-item">
        <a class="nav-link" [ngClass]="{'active': activeTab === 'home'}" 
        routerLinkActive="active"
        [routerLink]="['/home']"
         >HOME</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" [ngClass]="{'active': activeTab === 'contact'}" 
        routerLinkActive="active"
        [routerLink]="['/contact']"
        >CONTACT</a>
      </li>
    

    You can see a simple live example here, Stackblitz