Angular 2,使用href ='#'处理锚链接 [英] Angular 2, handle anchor links with href='#'

查看:78
本文介绍了Angular 2,使用href ='#'处理锚链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击任何具有href='#'的锚链接时,Angular路由器路径

When clicking any anchor link which has a href='#', the Angular router path

{ path: '', component: NologinComponent, pathMatch: 'full' }

已匹配,我应如何处理这些锚链接,以使具有href='#'的锚保持在同一页面上,即什么也不做.

is matched, How should I handle these anchor links so that anchor with href='#' stays on same page, i.e do nothing.

锚标记示例

<a class="title-logo" href="#"><img src="/Content/Images/Image1.png"></a>

还有一点要考虑,我在布局页面中使用了<base href="/" />,以便刷新角度停留在当前页面上,并从"/"寻找资源,而不是从当前组件内部寻找资源.

One More point to consider, i have used the <base href="/" /> in the layout page so that on refresh angular stays on current page and look for the resources from "/" not from inside the current component.

推荐答案

有一些选择:

选项1:

使用指令覆盖href属性:

@Directive({
  selector : '[href]'
})
export class MyLinkDirective {
  @Input() href: string;

  @HostListener('click', ['$event'])
  noop(event: MouseEvent) {
    if(this.href.length === 0 || this.href === '#') {
      event.preventDefault();
    }
  }
}

来源

我个人喜欢这种解决方案,因为它是全局的和有角度的.这是一个 stackblitz示例

Personally, I like this solution because it is global and angular. Here's a stackblitz example.

选项2

您可以同时使用css和href属性:

You can use css and ditch the href attribute all together:

a {
  cursor: pointer;
  user-select: none;
}

那么您的无效链接将是:

Then your inactive links would be:

<a class="title-logo"><img src="/Content/Images/Image1.png"></a>


选项3

CSS pointer-events:

a.noop {
   pointer-events: none;
}

用法

<a class="title-logo noop" href="#"><img src="/Content/Images/Image1.png"></a>

pointer-events如果在意某些浏览器(尤其是较旧的浏览器),可能会引起麻烦.您可以在此处看到兼容性列表.

pointer-events may cause trouble on some (especially older) browsers, if you care about them. You can see the compatibility list here.

这篇关于Angular 2,使用href ='#'处理锚链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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