简体   繁体   English

如何在Angular中嵌套routerLink

[英]How to have nested routerLink in Angular

I have a project in angular 7 我有一个关于Angle 7的项目

I have router links with <a> tag, and I have nested <a> tags that both have routerLink property, 我有带有<a>标签的路由器链接,并且有嵌套的<a>标签,它们都具有routerLink属性,

the issue I am facing is , the inner <a> route doesn't work 我面临的问题是,内部<a>路线不起作用

<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 改变a标签也跨不解决问题

<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 这是它的https://stackblitz.com/edit/angular-nested-router

In your stackblitz add the following function to your component class. 在您的stackblitz中,将以下函数添加到组件类中。 It receives the event as parameter and calls the stopPropagation function on it. 它接收事件作为参数,并在其上调用stopPropagation函数。

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. 参见我的stackblitz前叉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM