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

查看:87
本文介绍了如何在锚点上有条件地使用[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:

<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天全站免登陆