How to have nested routerLink in Angular

扶醉桌前 提交于 2019-12-11 01:08:20

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/53147005/how-to-have-nested-routerlink-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!