SatAj
SatAj

Reputation: 1979

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.

Upvotes: 4

Views: 1610

Answers (1)

John Montgomery
John Montgomery

Reputation: 7096

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.

Upvotes: 5

Related Questions