Search code examples
angularnavigationrouter

How to enable open link in new tab in click event in angular 12


My click event:

html:
 <div class="image"   (click)="onClickOperation(product);">
.......
</div>
TS:
onClickOperation(product: any): void {
    // debugger
    if (this.regularView) {
      if (this.details) {
        this.openLightbox(product);
      } else {
        this.router.navigate(['/product', product.productId]);
      }
    } else {
      this.router.navigate(['/store', product.shopId]);
      this.productsender.changeMessage(product);
    }
  }

its working fine how I want to implement right click to open link in new tab option .how can I do it need


Solution

  • If you mean you want to be able to open the link via the right-click menu then you need to pass routerLink to the a tag. There is the solution: How to enable "ctrl+click" with "routerLink" in Angular

    And an example:

    <a routerLink="/user/bob">link to user component</a>
    

    or

    <a [routerLink]="['/user/jim']">Jim</a>
    

    You need "a" tag because in HTML only this tag has the property to open links by HTML functionality.

    Information on how to use routerLink you can find in angular routerLink docs

    In your case probably you should use *ngIf make a condition to display a correct element with the correct URL.

    There is an example of how to make it. Conditionally add RouterLink or other attribute directives to an element in Angular 2

    If you want to replace the context menu with your function, just look at this issue: How to handle right click event in Angular app?