如何在Angular中嵌套routerLink [英] How to have nested routerLink in Angular

查看:170
本文介绍了如何在Angular中嵌套routerLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个7号角项目

我有带有<a>标签的路由器链接,并且我嵌套了同时具有routerLink属性

I have router links with <a> tag, and I have nested <a> tags that both have routerLink property,

我面临的问题是,内部<a>路由不起作用

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>

更改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>

这是 https://stackblitz.com/edit/angular-nested-router 为此

推荐答案

在您的stackblitz中,将以下函数添加到组件类中.它接收事件作为参数,并在其上调用stopPropagation函数.

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();
  }
}

在您的模板中做

<router-outlet></router-outlet>
<a routerLink="/comp1">
  Comp1
  <a routerLink="/comp2" (click)="stop($event)">
    Navigate to comp2 (Nested)
  </a>
</a>

请参阅我的 stackblitz 叉.

这篇关于如何在Angular中嵌套routerLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆