You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何用href调用函数且支持右键新标签页打开

解决方案

要同时实现左键调用Angular路由跳转、右键可在新标签页打开目标页面,核心是让<a>标签的href指向实际的目标URL,而非无效的脚本链接,同时保留点击事件的自定义逻辑。

步骤1:新增生成目标URL的方法

在组件类中添加一个方法,根据原有逻辑生成对应的路由URL字符串(利用Angular Router的createUrlTree方法确保URL正确):

getEventUrl(isDm: boolean, danceEvent?: DanceEvent): string {
  if (isDm) {
    if (danceEvent) {
      return this._router.createUrlTree(['preview', danceEvent.id], {
        relativeTo: this._route
      }).toString();
    } else {
      return this._router.createUrlTree(['preview'], {
        relativeTo: this._route
      }).toString();
    }
  } else {
    return this._router.createUrlTree(['/dance-event', this.danceEvent.id]).toString();
  }
}

步骤2:修改模板中的<a>标签

将href绑定到上述方法的返回值,同时在点击事件中调用原函数并阻止默认跳转行为(保留Angular单页路由的无刷新体验):

<a 
  [href]="getEventUrl(isDm, danceEvent)" 
  (click)="onEventNameClick(isDm, danceEvent); $event.preventDefault()"
  style="text-decoration: none; color:inherit;"
>
  <!-- 这里放置你原来的div内容 -->
</a>

原理说明

  • href绑定实际URL后,浏览器右键菜单的“在新标签页打开”会直接使用该URL,不会出现空白页;
  • 点击事件中添加$event.preventDefault(),阻止<a>标签的默认跳转行为,让左键点击仍走Angular的router.navigate逻辑,保持单页应用特性。

内容的提问来源于stack exchange,提问作者Xxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:37:12