Angular routerLink within [innerHTML]

一曲冷凌霜 提交于 2020-01-23 05:51:30

问题


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.

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

declare var $:any;

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...


回答1:


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);
      }
    }
  }
}




来源:https://stackoverflow.com/questions/45738371/angular-routerlink-within-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!