1

I use angular with optional parameters. I route to a location with navigate:

router.navigate(["route1"], { p1: v1 });

and I see the location

/route1;p1=v1

Now I try to navigate to

/route1;p1=v1 ;p2=v2

I search something like

router.navigate({ p2: v2 }, relative);

but I have problems finding a working syntax.

Mario
  • 278
  • 2
  • 15

1 Answers1

4

To allow the component route to have multiple optional parameters, inside your routing module, specify the route as follows:

const appRoutes: Routes = [
    ...
  {path: 'route1',component: MyComponent}
    ...
];

In the calling component that you wish to call MyComponent from, use the router navigate() method as follows:

router.navigate(['route1', {p1:value1,p2:value2}]);

Where value1 and value2 are variables within your calling component that you want to bind to the parameters p1 and p2.

The above should match parameters p1, p2 or p1 and p2 for the route.

In a HTML template, call the above using the following router link:

<a [routerLink]="['/route1', {p1:value1, p2:value2}]" .. />

The router URL link will then resolve to:

/route1;p1=value1;p2=value2

The following router link:

<a [routerLink]="['/route1', {p1:value1}]" .. />

Will resolve to the URL:

/route1;p1=value1

And the following router link:

<a [routerLink]="['/route1', {p2:value2}]" .. />

Will resolve to the URL:

/route1;p2=value2

Note: that if you omit the brackets [] in your router link, then the following error will appear with parameters are included:

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

Within your component MyComponent, read the parameters using paramMap as follows:

const p1 = this.route.snapshot.paramMap.get('p1');
const p2 = this.route.snapshot.paramMap.get('p2');

The route parameters paramMap are an observable that can change when the same route is called within an application, so it is recommended to subscribe to it within the component as follows:

routingSubscription: Subscription;

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

ngOnInit(): void {
    let route = this.activatedRoute.snapshot;
    let urlSegments = route['_urlSegment'].segments;
    let relativePath: string = '';
    urlSegments.forEach((pathSegment: UrlSegment) => {
        relativePath = relativePath.concat(pathSegment.path, '/');
    });

    this.routingSubscription = this.activatedRoute.paramMap
      .subscribe((params: ParamMap) => {
            const firstParam: string = params.get('p1');
            const secondParam: string = params.get('p2');

            if (firstParam && !secondParam)
            {
              let mySecondParam: string = "2";
              this.router.navigate(
                  [relativePath, {p1:firstParam,p2:mySecondParam}]);
            }
      });
}

The example above will allow a route to the component with the first parameter then re-route back with the relative path of the original route. This should also work within a feature module.

Alternatively, the relative path can specified without quantifying the individual path segments in the active route. This can be done using the relativeTo option within router.Navigate().

To make use of relativeTo, import NavigationExtras interface as follows:

import { NavigationExtras } from '@angular/router';

We can then specify and extend the navigation as follows:

this.router.navigate(
    [{id1:firstParam,id2:mySecondParam}], 
    { relativeTo: this.activatedRoute }
);
Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
  • As you can see here: https://stackoverflow.com/a/44865817/11442461 you specify required parameters. I ask for optional parameters. – Mario Oct 05 '21 at 14:38
  • Just updated answer. Corrected the router link and app route. – Andrew Halil Oct 05 '21 at 15:06
  • For a solution like your example, I need to know existence and value of p1. But I like to navigate on my location and add the parameter p2 without any other change on my location. If another function adds an additional parameter, I don’t like to touch the parameter. Do you understand the difference of my specification? – Mario Oct 06 '21 at 12:50
  • Using ActivatedRoute within the component, you can find the route path and parameters for the route,. Depending on existing parameters in the route, include the extra optional parameter not used in Router.Nagivate(..). – Andrew Halil Oct 06 '21 at 14:35
  • I have included the relativeTo routing option in the answer. – Andrew Halil Oct 07 '21 at 12:21