Issue when using routerLinkActive in parent route with dynamically generated child route

Discussão em 'Angular' iniciado por Sandeep K Nair, Setembro 27, 2024.

  1. I have the following parent route


    @Component({
    selector: 'app-layout',
    standalone: true,
    imports: [CommonModule, RouterModule],
    templateUrl: './layout.component.html',
    styleUrl: './layout.component.css',
    template: `
    <ul>
    @for (project of projects; track project.id) {
    <li>
    <a
    class="link"
    [routerLink]="['projects', project.id, project.defaultView]"
    routerLinkActive="active"
    >{{ project.name }}</a
    >
    </li>
    }
    </ul>
    `
    })
    export default class LayoutComponent {
    projects = [
    { id: 1, name: 'My aweosme project', defaultView: 'overview' },
    { id: 2, name: 'App v1.0', defaultView: 'calendar' },
    ];
    }



    and the following child routes when a parent route is clicked


    @Component({
    selector: 'app-project',
    standalone: true,
    imports: [CommonModule, RouterModule],
    templateUrl: './project.component.html',
    styleUrl: './project.component.css',
    template: `
    <ul>
    <li>
    <a class="link" [routerLink]="['overview']" routerLinkActive="active"
    >Overview</a
    >
    </li>
    <li>
    <a class="link" [routerLink]="['calendar']" routerLinkActive="active"
    >Calendar</a
    >
    </li>
    <li>
    <a class="link" [routerLink]="['settings']" routerLinkActive="active"
    >Settings</a
    >
    </li>
    </ul>

    <router-outlet></router-outlet>
    `
    })
    export default class ProjectComponent implements OnInit {
    projectId!: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit(): void {
    this.route.params.pipe(tap(({ id }) => (this.projectId = id))).subscribe();
    }
    }



    When I navigate from parent its going to the correct default child route for example when i click My aweosme project link its taking me to child route overview page and its adding the active class on my parent.

    Now when I manually click on child links calendar link the active class from the parent link gets removed.

    How should I preserve the active class on the parent keeping the defaultView navigation to the child route intact [routerLink]="['projects', project.id, project.defaultView]"

    A minimal reproduction of my issue is shown here

    Default navigation working [​IMG]

    Child navigation removing the active class from parent [​IMG]

    Continue reading...

Compartilhe esta Página