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

查看:28
本文介绍了[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]);
    }
});

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

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