Search code examples
javascriptangularangular-routingangular-router

adding a right click event for nav menu in angular


I am working in an angular app, navigation part which need right click unable and open as new tab tooltip when I try to add routerLink it becomes 404 error. could anyone help me to add right click event for this , my code is as below

<ng-container *ngFor="let gotolink of allLInks">
                            <a
                              class="nav"
                              (click)="onClicktonav(gotolink?.path, gotolink.name)"    
 [routerLink]="['/gotolink?.path']" routerLinkActive="router-link-active"                        >
                                                            <span class="Header-user-link-text">
                                {{ gotolink.name }}
                              </span>
                            </a>
                          </ng-container>

above my html

onClicktonav(path, name) {
    if (name === 'about') {
      this.gtmService.pushGTMTags('aboutpage', {
        fromPage: 'rightsidebar',
      });
    } else if (title === 'services') {
    } else if (title === 'contact') {
    } else if (title === 'blog') {
      this.gtmService.pushGTMTags('blogpage');
    }
    this.router.navigate([path]);
  }

now the links working right click is throwing 404 error I want to make right click also work for this

[routerLink]="['/gotolink?.path']" routerLinkActive="router-link-active"
I added this inside html and was expecting right click work


Solution

  • To enable right-click functionality on your Angular app without causing a 404 error, you need to handle the right-click event separately. You can use a custom right-click event in Angular by using the (contextmenu) event. Here's how you can make it work:

    <ng-container *ngFor="let gotolink of allLInks">
      <a class="nav" (click)="onClicktonav(gotolink?.path, gotolink.name)" (contextmenu)="onRightClick($event, gotolink?.path)">
        <span class="Header-user-link-text">
          {{ gotolink.name }}
        </span>
      </a>
    </ng-container>
    

    and ts :

    onRightClick(event: MouseEvent, path: string) {
      event.preventDefault(); // Prevent the default context menu from showing up
      // Your custom code for handling the right-click event
      window.open(path, '_blank'); // Open the link in a new tab
    }