[innerHTML]中的Angular routerLink [英] Angular routerLink within [innerHTML]

查看:72
本文介绍了[innerHTML]中的Angular routerLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法,当将标准a [href]链接动态加载到[innerHTML]时,该链接可以充当routerLinks.看来这不是标准的东西,我找不到能满足我需求的东西.

I have been looking around for a way to enable standard a[href] links to act like routerLinks when loaded dynamically into [innerHTML]. It doesn't seem to be something that works as standard and I couldn't find anything that did what I needed.

我有一个可行的解决方案,但想知道是否有人知道这样做的更好方法,或者我可能会遇到这种潜在问题.

I have a working solution but wondered if anybody knows of any better ways to do this or any potential issues I might run into doing it this way.

我从我的app-routing.module.ts内部使用jQuery,所以我声明了变量:

I am using jQuery from inside my app-routing.module.ts so I declare the variable:

declare var $:any;

然后,我找到所有具有href属性的锚,这些锚也没有routerlink属性.然后,我可以获取路径名,并告诉路由器单击它来导航至该路径.

I then find all anchors with the href attribute that do not also have the routerlink attribute. I can then grab the pathname and tell the router to navigate to it on click.

$(document).on('click', `a[href]:not("a[routerlink]"):not("a[href^='mailto:']"):not("a[href^='tel:']")`, function(e){
    if(location.hostname === this.hostname || !this.hostname.length){
        e.preventDefault();
        router.navigate([this.pathname]);
    }
});

这似乎可以完成工作,但是我认为必须有一种更"Angular"的方式来做到这一点...

This seems to do the job but I thought there must be a more 'Angular' way of doing this...

推荐答案

这可能不是最好的方法,但是您可以使用RendererElementRef将事件监听器原样添加到锚标记中在本文中进行了讨论.

This may not be the best way to do it, but you can use Renderer and ElementRefto add an event listener to the anchor tags as is discussed in this article.


@Component({
  selector: 'app-example-html',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.less'],
})
export class ExampleComponent implements AfterContentInit {

  private clickListeners: Array<(evt: MouseEvent) => void> = [];

  constructor(
    private router: Router,
    private el: ElementRef,
    private renderer: Renderer2,
  ) { }

  ngAfterViewInit() {
    const anchorNodes: NodeList = this.el.nativeElement.querySelectorAll('a[href]:not(.LinkRef)'); // or a.LinkPage

    const anchors: Node[] = Array.from(anchorNodes);

    for (const anchor of anchors) {
      // Prevent losing the state and reloading the app by overriding the click event
      const listener = this.renderer.listen(anchor, 'click', (evt: MouseEvent) => this.onLinkClicked(evt));
      this.clickListeners.push(listener);
    }
  }

  private onLinkClicked(evt: MouseEvent) {
    evt.preventDefault();
    if (evt.srcElement) {
      const href = evt.srcElement.getAttribute('href');
      if (href) {
        this.router.navigateByUrl(href);
      }
    }
  }
}


这篇关于[innerHTML]中的Angular routerLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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