如何在Angular中嵌套routerLink [英] How to have nested routerLink in Angular
问题描述
我有一个 angular 7 项目
我有带有 标签的路由器链接,并且我有嵌套的
标签,它们都具有
routerLink
属性,
Comp1<a [routerLink]="['./comp2']">导航到 comp2(嵌套)</a></a>
如果我将它分开,这将起作用
<a [routerLink]="['./comp2']">导航到 comp2(未嵌套)</a>
我也试过下面的代码,还是一样
Comp1<a [routerLink]="['./comp2']" (click)="$event.preventDefault()>导航到 comp2(嵌套)</a></a>
将 a
标签更改为 span 也不能解决问题
这是https://stackblitz.com/edit/angular-nested-router 因为它
在您的 stackblitz 中,将以下函数添加到您的组件类中.它接收事件作为参数并对其调用 stopPropagation
函数.
import { Component } from '@angular/core';@成分({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {name = '角度';停止(事件:事件){event.stopPropagation();}}
在你的模板中做
<a routerLink="/comp1">Comp1<a routerLink="/comp2" (click)="stop($event)">导航到 comp2(嵌套)</a></a>
查看我的 stackblitz 分支.
I have a project in angular 7
I have router links with <a>
tag, and I have nested <a>
tags that both have routerLink
property,
the issue I am facing is , the inner <a>
route doesn't work
<a [routerLink]="[ './comp1']">
Comp1
<a [routerLink]="['./comp2']">
Navigate to comp2 (Nested)
</a>
</a>
this is working if I separate it
<div>
<a [routerLink]="['./comp2']">
Navigate to comp2 (Not Nested)
</a>
</div>
Also I tried the below code and still same
<a [routerLink]="[ './comp1']">
Comp1
<a [routerLink]="['./comp2']" (click)="$event.preventDefault()>
Navigate to comp2 (Nested)
</a>
</a>
changing a
tags to span also doesn't solve the issue
<span [routerLink]="[ './comp1']" >
Comp1
<span [routerLink]="['./comp2']" (click)="$event.preventDefault()">
Navigate to comp2 (Nested)
</span>
</span>
Here is the https://stackblitz.com/edit/angular-nested-router for it
In your stackblitz add the following function to your component class. It receives the event as parameter and calls the stopPropagation
function on it.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
stop(event: Event) {
event.stopPropagation();
}
}
In your template do
<router-outlet></router-outlet>
<a routerLink="/comp1">
Comp1
<a routerLink="/comp2" (click)="stop($event)">
Navigate to comp2 (Nested)
</a>
</a>
See my stackblitz fork.
这篇关于如何在Angular中嵌套routerLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!