Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular routing with optional parameters

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.

like image 796
Mario Avatar asked Oct 18 '25 07:10

Mario


1 Answers

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 }
);
like image 131
Andrew Halil Avatar answered Oct 19 '25 22:10

Andrew Halil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!