Ste*_*eve 6 angular angular-router
我一直在寻找一种方法来启用标准的[href]链接,以便在动态加载到[innerHTML]时充当routerLinks.它似乎不是标准的东西,我找不到任何我需要的东西.
我有一个可行的解决方案,但想知道是否有人知道有任何更好的方法来做到这一点或任何潜在的问题,我可能会这样做.
我在app-routing.module.ts中使用jQuery,所以我声明了变量:
declare var $:any;
Run Code Online (Sandbox Code Playgroud)
然后我找到所有具有href属性但没有routerlink属性的锚点.然后我可以获取路径名并告诉路由器在点击时导航到它.
$(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]);
}
});
Run Code Online (Sandbox Code Playgroud)
这似乎做了这个工作,但我认为必须有一个更"'角度'的方式这样做......
这可能不是最好的方法,但您可以使用Renderer和ElementRef将事件侦听器添加到锚标记,如本文中所述。
@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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |