Search code examples
angularangular-routing

Angular2+ on click event if normal click but route if middle click or new window


I'm trying to set up a link so that if a user clicks normally an area expands on the page, but if they click it with middle button (or any type of open in new window button) then the user navigates to the link.

Here is an example of something that does not work. Just setting the href tag wont work either, both href and the below example navigate to the page no matter how the link is clicked.

Using the below code the variable is also set, but the user is quickly navigate away just after.

<a class="commentBubble" (click)="showComments = true;" [routerLink]="['/b', blogPost.Id, blogPost.url]">0</a>

Solution

  • You would need to call a function when the user clicks and pass the click event into it:

    <a (click)='onClick($event)'></a>
    

    In this function you can differentiate bewteen these two cases like this:

    public onClick(event: MouseEvent): void {
        if (event.which === 2 ){
            /** Middle mouse click */
            this.router.navigate(['/b', this.blogPost.Id, this.blogPost.url])
        } else {
            /** Normal click */
            this.showComments = true;
        }
    }