Angular 2: multiple for sub routes

2020-07-11 08:34发布

问题:

With Angular 2, is it any way to have sub route not displaying into the main tag

<router-outlet></router-outlet>

For example :

url : "http://mywebsite.com/"
MainComponent.ts
@Component({
    ...
    template:'<router-outlet></router-outlet>'
    ...
})
@RouteCongif([
    {path: '/products', name:'Product', component: Product}
])

This displays the sub component into the <router-outlet> tag

All right, now is it possible to have this kind of configuration :

url : "http://mywebsite.com/products"
ProductComponent.ts
@Component({
    template: `
        ...
        <div> My list of products ! </div>
        ...
        <a [RouteLink]="['ProductDetails', {slug-product-details:product.slug}]"> 
           {{ product.name }} Details 
        </a>
        ...
        <sub-router-outlet></sub-router-outlet>
    `
})
@RouteConfig([
     {path: '/:slug-product-details', name:'ProductDetails', component: ProductDetailsComponent},
])

And

url : "http://mywebsite.com/products/one-product-details"
ProductDetailsComponent.ts
@Component({
    ...
    template : `
         <div> Details of the product : </div>
         ...
    `
    ...
})

I want to keep the usage of the router with the auto designed url and diplay the route and the details template into this sort of <sub-router-outlet> tag.

Thank you for your help.

回答1:

WARNING: The code below only works on Angular2 Beta

You can implement sub routing. Your file structure should be similar like this.

app.ts

@RouteConfig([
    ...
    { path: '/product/...', component: Product, name: 'Product'}
    { path: '/home', component: Home, name: 'Home'}
    ...
])
export class App { }

product.ts

@Component({
    selector: 'product',
    templateUrl: 'app/components/product/product.html',
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
   ...
   { path: 'product-one', component: ProductOne, name: 'Product-one' },        
   { path: 'product-two', component: ProductTwo, name: 'Product-two', useAsDefault: true },
   ...
])
export class Product {
    constructor(location: Location, public router: Router) {}

    goToProductOne() {
        this.router.navigate(['Product','Product-one'])
    }
}

product.html

...
<a [routerLink]="['./Product-one']"> Product One </a>
<a [routerLink]="['/Home']"> Home </a>
...

Where ['./Product-one'] is a subroute and ['/Home'] is a parent route