如何在锚点上有条件地使用 [href] 或 [routerLink]? [英] How can I conditionally use either [href] or [routerLink] on an anchor?

查看:35
本文介绍了如何在锚点上有条件地使用 [href] 或 [routerLink]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有条件地将同一个锚链接指向本地或外部资源.我试过

I need for the same anchor link to be pointed conditionally locally or to external resource. I tried

<a [href]="outside?externalUrl:null"  [routerLink]="outside?[]:['/route',id]" >test</a>

但它不起作用.我没有收到任何错误,但它指向同一个本地页面并忽略外部 URL.有什么想法吗?

But it doesn't work. I don't get any errors, but it points to the same local page and ignores the external URL. Any ideas?

另一种选择是构建链接,但我找不到任何文档如何在服务中访问 routerLink

Another option would be to construct the link, but I can't find any docs how to access routerLink inside a service

我知道我可以用 *ngIf 克隆整个链接,但我不想这样做,我的链接包含一个带有很多选项的视频标签

I know I can clone the whole link with *ngIf but I don't want to do it, my link contains a video tag with a buch of options

推荐答案

最简单的方法是使用 *ngIf/else:

The simplest way would be to use *ngIf / else:

<ng-container *ngIf="outside; else internalBlock">
  <a [href]="externalUrl">External</a>
</ng-container>

<ng-template #internalBlock>
  <a [routerLink]="['/route', id]">Internal</a>
</ng-template>

EDIT#1:(丑陋的解决方法)

既然你不想使用*ngIf(我还是不明白为什么),你可以这样做:

Since you don't want to use *ngIf (I still don't understand why), you can do this:

模板:

<a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a>

组件:

handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void {
  if (outside) {
    window.location.href = externalUrl;
    // You can also use Location class of Angular
  } else {
    this.router.navigate([`${internalUrl}/${internalId}`]);
  }
}

这篇关于如何在锚点上有条件地使用 [href] 或 [routerLink]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆