Angular 4 Dynamic Number of Route Parameters

Viewed 2274

In my Angular 4 project I have a container component at route:

{ path: 'someComponent', component: SomeComponentContainerComponent },

which when visited, it would at random create one or more instances of SomeComponent inside this container component and change the URL to look like this:

'localhost:4200/someComponent/id1/id2/id3/...'

with the number of id depending on how many instances are created. If a user visits a URL like the above that has one or more optional id, it should be handled by the container object to create a corresponding number of instances of SomeComponent with the given ids.

For a static number of these optional route parameters I could try the following:

{ path: 'someComponent', component: SomeComponentContainerComponent },

{ path: 'someComponent/:id1', component: SomeComponentContainerComponent },

{ path: 'someComponent/:id1/:id2', component: SomeComponentContainerComponent },

...

My question is how can I catch these optional route parameters when the number of them is not always the same?

Any help is much appreciated, thanks in advance.

1 Answers

The following solution worked for me:

In module.ts

{
    path: 'someComponent',
    children: [{path: '**', component: SomeComponentContainerComponent}]
}

and in component.ts

constructor(private route: ActivatedRoute){}

ngOnInit(){
    this.route.url.subscribe((segments: UrlSegment[]) => {
        for(var i = 0; i < segments.length; i++){
            console.log("param: " + segments[i]);
        }
    });
}
Related