首页 文章

Angular 4:子路由中的多个(命名)路由器出口:支持?

提问于
浏览
20

我有一个主 - 细节设置,还有一个用于“编辑”列表项的部分,所有这些都在1个登陆路线上(在我的示例应用中,路线是/ stuff) . 详细信息组件使用默认路由器插座填充,位于/ stuff /:index . 我试图通过route / stuff /:index / edit将HTML发送到编辑部分的另一个路由器插座,但Angular似乎无法识别路由 .

我继续把Bitbucket的情况概括为:

https://bitbucket.org/squirrelsareduck/angularrouting/

无论如何,一般错误是这样的:

错误:无法匹配任何路由 . 网址细分:'stuff / 1 / edit'

代码中最相关的部分:

路线定义:

const routes: Routes = [
  { path: 'stuff', component: AComponent, children:[
    { path: ':index', component: BComponent},
    { path: ':index/edit', component: EditComponent, outlet:'editsection'}
  ]}
];

a.component.html:

<ul>
  <app-listitem
    *ngFor="let a of items; let indexOI = index;"
    [index]="indexOI"
  [contentOI]="a">
  </app-listitem>
</ul>
<router-outlet></router-outlet>
<router-outlet name="editsection"></router-outlet>

b.component.html:

<p>
  Detail section works! {{ index }}
  <button
    type="button"
    [routerLink]="['edit',{outlets:{editsection:'/stuff/:index/edit'}}]">
    Edit
  </button>
</p>

edit.component.html(不太相关,但重要的是要识别)

<p>
  edit section works!
</p>

2 回答

  • 9

    b.component.html 中应用这些更改,它应该按预期工作 .

    <p>
      Detail section works! {{ index }}
     <button type="button"
       [routerLink]="['/stuff',{outlets:{editsection:':index/edit'}}]">Edit</button>
    </p>
    

    对于动态URL,使用 routerLink ,首先,提及您要去的路线,然后如图所示定义出口和子路线 .

  • 22

    一种更强大的方法是基于组件的路由 . 因此,任何组件都可以定义自己的子路由,因此路由不会在ngModule级别上传播 . 例如...

    import { Component} from '@angular/core';
    import { Routes } from '@angular/router';
    
    @Routes({
        path : "/article/22",
            component : ArticleDetailsComponent,
            outlet : "article-details"
    },
    {
        path : "/article/22",
            component : ArticlePictureComponent,
            outlet : "article-picture"
    })
    @Component({
      selector: 'my-component',
      template: '
            <div> 
                <outlet name="article-details"></outlet> 
            <div>
            <div>
                <outlet name="article-picture"></outlet>
            </div>
    ',
    })
    
    export class MyComponent {
      title = 'app works!';
    }
    

    这个例子可能不是最好的......但是这种方法在设计复杂的SPA架构时让我更加自由和强大!路由封装在组件级别,当我销毁组件时,路由被删除 .

相关问题