Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent overriding of parent routerLink over child

I have nested navigation(routes) in my example

<ul>
    <li *ngFor="let route of routes" [routerLink]="route.link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
        {{route.name}}</span>
        <!-- Secondary navigation (if exists) -->
        <ul *ngIf="route.children" class="secondary">
          <li *ngFor="let item of route.children" [routerLink]="item.link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
            {{item.name}}
          </li>
        </ul>
    </li>
</ul>

Every time I click on parent item, it navigates to the appropriate link, but on clicking any of the child item, instead of respective child link, it navigates to parent <li> routes as the whole child <ul> is part of this parent <li> How can I prevent this parent routerLink in such nested cases? Appriciate your help.

like image 786
SatAj Avatar asked Oct 31 '25 15:10

SatAj


1 Answers

When you click a child element, it triggers the click event on all the parent elements as well. Since they run in order, the outermost one "wins" in the case of navigation.

Add (click)="$event.stopPropagation()" (or use (click)="someFunction($event)" and call stopPropagation() inside the function if you need to run other logic on the click as well) to the child element to prevent it from bubbling.

like image 52
John Montgomery Avatar answered Nov 03 '25 22:11

John Montgomery