简体   繁体   English

Angular 嵌套子路由

[英]Angular Nested Child Routing

I am learning use of multiple router-outlet.我正在学习使用多个路由器插座。

While using navigateBy function of router, i am not able to view my child route and getting error.使用路由器的navigateBy function 时,我无法查看我的子路由并出现错误。 But if i access it via routerLink in html i get the desired output.但是,如果我通过html中的 routerLink 访问它,我会得到所需的 output。

So in below code, navigation to songs is working, but navigation to films is not.所以在下面的代码中,导航到歌曲是有效的,但导航到电影不是。

const routes = [
  {
    path: 'bollywood',
    component: BollywoodComponent,
    children: [
      {
        path: 'films',
        component: FilmsComponent,
      },
      {
        path: 'songs',
        component: SongsComponent,
      },
    ],
  },
  {
    path: 'hollywood',
    component: HollywoodComponent,
  },
  {
    path: 'tollywood',
    component: TollywoodComponent
  },
];

App Component html应用组件 html

<button class="f-margin-16" (click)="navigateToBollywoodSection()"> Bollywood </button>
<button class="f-margin-16"  (click)="navigateToHollywoodSection()"> Hollywood </button>
<button class="f-margin-16" [routerLink]="['tollywood']" > Tollywood </button>

<br>
Router outlet starts now

<router-outlet> </router-outlet>

Bollywood Component html宝莱坞组件 html

<button (click)="navigateToFilms()"> Films </button>
<button [routerLink]="['songs']"> Songs </button>

<router-outlet> </router-outlet>
  navigateToFilms() {
    this.router.navigate(['/films']);
  }

StackBitz Link https://stackblitz.com/edit/angular-ivy-1nzkus?file=src/app/bollywood/bollywood.component.html StackBitz 链接https://stackblitz.com/edit/angular-ivy-1nzkus?file=src/app/bollywood/bollywood.component.html

In router.navigate , you can pass relativeTo as the second param.router.navigate中,您可以将relativeTo作为第二个参数传递。

navigateToFilms() {
    this.router.navigate(['films'], {relativeTo: this.activatedRoute} );
}

This way navigation will happen relative to the current route.这样导航将相对于当前路线发生。 In the constructor you can add the ActivatedRoute dependency.在构造函数中,您可以添加ActivatedRoute依赖项。

constructor(private activatedRoute: ActivatedRoute) {}

If you use <button [routerLink]="['songs']"> Songs </button> , the navigation by default happens relative to the current route.如果您使用<button [routerLink]="['songs']"> Songs </button> ,默认情况下导航会相对于当前路线发生。

Use it like this像这样使用

this.router.navigate(['bollywood/films']); this.router.navigate(['宝莱坞/电影']);

If you want to use a navigation route then you can use this code.如果您想使用导航路线,则可以使用此代码。 because without a specific parent route you can't access child routing.因为没有特定的父路由,您将无法访问子路由。

this.router.navigate(['/bollywood/films']);

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

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