gpt4 book ai didi

[innerHTML] 中的 Angular routerLink

转载 作者:太空狗 更新时间:2023-10-29 17:28:52 26 4
gpt4 key购买 nike

我一直在寻找一种方法,使标准的 a[href] 链接在动态加载到 [innerHTML] 时可以像 routerLinks 一样工作。它似乎不是标准的东西,我找不到任何能满足我需要的东西。

我有一个可行的解决方案,但想知道是否有人知道执行此操作的任何更好的方法或我这样做可能会遇到的任何潜在问题。

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

declare var $:any;

然后我找到所有具有 href 属性但不具有 routerlink 属性的 anchor 。然后我可以获取路径名并告诉路由器在单击时导航到它。

$(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 ”的方式来做到这一点......

最佳答案

这可能不是最好的方法,但您可以使用 RendererElementRef 将事件监听器添加到 anchor 标记,如 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com