我有一个Web组件,该组件使用简单的锚标记和带有指向路径的href。
单击链接后,将重新加载应用程序。
我无法使用routerLink(Web组件不是Angular)。避免页面重新加载的最佳方法是什么?
要解决此问题,我会监听“ a”标签的点击,如果它不包含“ routerlink”属性,则会阻止默认行为。
@HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}