简体   繁体   中英

Angular 8 routerLinkActive with params

I have two tabs on my sidebar, one for Open chats , one for Closed chats . When I select the Open chats tab, it becomes bold. When I selected the Closed chats tab, both tabs become bold. If I add [routerLinkActiveOptions]="{ exact: true }" to the a tag of Open chats it fixes the problem, but it opens up a new problem. When I select a chat within the Open chats component, the url switched to .com/messenger/{randomString} the Open chats tab stays bold which is good, but when I refresh the page and the url stays, the Open chats tab is no longer bold/active. How would I accomplish both keeping the messenger/complete and messenger separate, while still allowing messenger and messenger/:id to stay active together.

Note: I technically also need messenger/complete and messenger/complete/:id to stay active together in the same way

sidebar html

      <a class="inboxLabel openChatsLabel" routerLink="/messenger" routerLinkActive="selectedLabel selectedOpen">
        <div></div>
        <p>Open Chats</p>
      </a>
      <a class="inboxLabel closedChatsLabel" routerLink="/messenger/complete"
        routerLinkActive="selectedLabel selectedClosed">
        <div></div>
        <p>Closed Chats</p>
      </a>

routing module

  {
    path: 'messenger',
    component: OverviewComponent,
    canActivate: [AuthGuard],
  },
  {
    path: 'messenger/:id',
    component: OverviewComponent,
  },
  {
    path: 'messenger/complete/:id',
    component: OverviewComponent,
  },

Alright, figured it out!

sidebar ts

import { Component, OnInit } from '@angular/core';
import { Router, Event, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css'],
})
export class SidebarComponent implements OnInit {
  completeTab: boolean;

  constructor(private router: Router) {}

  ngOnInit() {
    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        this.completeTab = event.url.includes('/complete') ? true : false;
      }
    });
  }
}

sidebar html

  <a class="inboxLabel openChatsLabel" routerLink="/messenger" routerLinkActive="selectedLabel selectedOpen"
        [ngClass]="{'selectedLabel': !this.completeTab, 'selectedOpen' : !this.completeTab}">
        <div></div>
        <p>Open Chats</p>
      </a>
      <a class="inboxLabel closedChatsLabel" routerLink="/messenger/complete"
        routerLinkActive="selectedLabel selectedClosed">
        <div></div>
        <p>Closed Chats</p>
      </a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM