类似的问题已被问过多次,但我无法解决这个问题。例如,here是一些对大多数人不起作用的答案。这可能不是问题本身,但是我正在ng应用程序中尝试解决此问题。
我希望链接在单击后能正常工作。另外,我希望包含链接的项目可双击,以打开到路由器出口侧拆分区域的链接。所以在我的导航菜单中,我有:
<li *ngIf="propertiesTabVisible" class="nav-item tab-nav-item"
[routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'
(dblclick)="toggleTab('/properties/' + sessionId)">
<a class="nav-link" [routerLink]='["/properties", sessionId]'
[class.disabled]="(propertiesLinkDisabled | async)"
(click)="navigateWithDelay('/properties/' +sessionId)">
<mat-icon class="tab-nav-item-icon">assignment</mat-icon>
</a>
</li>
和在component.ts中:
private block = true;
private isCancelled = false;
private delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
private async sleepExample(url: string) {
await this.delay(200);
if (!this.block) {
this.router.navigate([url]);
}
}
navigateWithDelay(url: string) :boolean {
this.block = true;
this.isCancelled = false;
this.sleepExample(url).then(() => {
if (!this.isCancelled) {
this.block = false;
}
});
return false;
}
toggleTab(url: string) {
this.isCancelled = true;
toggleTabVisibility(url);
}
但是,这不起作用。即使两个处理程序都被调用,并且它们在路由器出口的顶部按我预期的方式工作,所以导航发生了。如何防止链接点击在Click-hanlder中传播?
答案 0 :(得分:0)
here说明了$ event.stopPropagation()和; $ event.preventDefault()在routerLink中不起作用的原因。
这是一个工作示例,其中click事件在锚点内的mat-icon中移动,并且处理程序都调用了这两者:
$event.stopPropagation();
$event.preventDefault();
.html:
<li *ngIf="propertiesTabVisible" class="nav-item tab-nav-item" [routerLinkActive]='["link-active"]' [routerLinkActiveOptions]='{ exact: true }'
(dblclick)="toggleTab('/properties/' +sessionId)">
<a class="nav-link" [routerLink]='["/properties", sessionId]' [class.disabled]="(propertiesLinkDisabled | async)">
<mat-icon class="tab-nav-item-icon" (click)="navigateWithDelay($event, '/properties/' +sessionId)">assignment</mat-icon>
</a>
</li>
.ts:
toggleTab(url: string) {
this.isCancelled = true;
this.ngRedux.dispatch(this.actions.toggleWindowUrl({
windowId: this.tabService.windowId,
url: url,
isSplit: true
}));
}
private isCancelled = false;
private delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
private async waitForDoubleClick() {
await this.delay(200);
}
navigateWithDelay($event: any, url: string) {
this.isCancelled = false;
$event.stopPropagation();
$event.preventDefault();
this.waitForDoubleClick().then(() => {
if (!this.isCancelled) {
this.router.navigate([url]);
}
});
}