无法在 Angular 中设置到指定出口的路由

Can't set up routing to a named outlet in Angular

我有三个命名路由器插座,如下所示。

...
<router-outlet name="menus"><router-outlet>
<router-outlet><router-outlet>
<router-outlet name="footer"><router-outlet>
...

在标记中,我想将第一个 menus 路由到其中包含某些子菜单垃圾的组件,如 shown in the docs

<ul *ngFor="let main of menus;" 
    routerLink="[{outlets:{menus:[{{main.link}}]}}]" 
    class="nav-items">{{main.header}}

我收到的错误是这样的:

Error: Cannot match any routes. URL Segment: '%5B%7Boutlets:%7Bmenus:%5Bsubmenu1%5D%7D%7D%5D'

我不知道语法有什么问题。用谷歌搜索我的指甲,但没有找到 简单粗暴的 示例 routerLink 版本显示如何在指定的出口中指向路线。

编辑: 根据评论和示例,我需要重新编写正在使用的代码,但仍然出现相同的错误。在标记中:

<ul *ngFor="let main of menus;" 
    (click)="pullMenu(main.link)" 
    class="nav-items">{{main.header}}

然后,在 TS:

constructor(private router: Router, private route: ActivatedRoute) { }

pullSubmenu(input) {
  console.log(input);
  this.router.navigate(
    [{ outlets: { menus: [input] } }], 
    { relativeTo: this.route });
}

现在,我收到以下错误(submenu1 是配置路径的名称)。

Error: Cannot match any routes. URL Segment: 'submenu1'

我的路由在模块中是这样设置的

const routes: Routes = [
  { path: "submenu1", component: Submenu1Component },
  { path: "submenu2", component: Submenu2Component }
];

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    MainAreaComponent,
    Submenu1Component,
    Submenu2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

您需要使用评估版[routerLink]:

<ul *ngFor="let main of menus;" 
    [routerLink]="[{outlets:{menus:[{{main.link}}]}}]" 
    class="nav-items">{{main.header}}

作为替代方案,您可以模拟 routerLink。这是它的作用的要点:

  @HostListener('click')
  onClick(): boolean {
    const extras = {
      skipLocationChange: attrBoolValue(this.skipLocationChange),
      replaceUrl: attrBoolValue(this.replaceUrl),
    };
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

因此,这里是使用 navigate 而不是 navigateByUrl 的设置:

   @Component({
      template: `
        <ul *ngFor="let main of menus;" (click)="[{outlets:{menus:[{{main.link}}]}}])"
        class="nav-items">{{main.header}}
      `
   ...
   class MyComponent {
      constructor(router: Router, route: ActivatedRoute) {}

      navigate(commands) {
         this.router.navigate(commands, {relativeTo: this.route})

您不能使用 routerLink 的未计算版本,因为它将命令作为字符串读取,如果您在命令中有 outlets,字符串将不起作用。请参阅 Navigation to secondary route URL for routerLink attribute 了解原因。