Match a route with "localhost:4200/test-(dynamic parameter)" in Angular 7


Problem summary: It's one of those friendly URL's that will be sent and inside the parentheses will come the abbreviation of the city's airport, I need the route to be activated when it comes with these parameters.

Ex: /voos-sao-paulo(gru) voos- /voos-sao-paulo(gru) based on this URL route voos- (which is the job of the matcher function in stackblitz) I need to make a request passing sao-paulo and gru (which will be extracted from the url) which is Guarulhos airport for API. The parameters of the city and the acronym of the airport will be dynamic and will have others such as date, other airports and so on.

The stackblitz matcher function works because all the URLs that will come will have to start with voos- .

The problem is that what comes inside the ( ) doesn't match the route and Angular throws an error and I can't get what comes in the URL, if a route without the ( ) only with gru the route enters the function matcher and works as expected.

StackBlitz simulating the problem


In your AppComponent logo in ngOnInit check the window.location.pathname which is what the angular router will analyze to find the routes.

Remember to insert into the main component of your application.

if(window.location.pathname.includes('(') || window.location.pathname.includes(')')) {
   window.location.pathname = window.location.pathname.replace(/\(/g, '%28').replace(/\)/g, '%29');


Another alternative is to put a script tag in your index.html right after the app-root tag closes the content below.

<script> window.history.pushState("", "", window.location.pathname.replace(/\(/g, '%28').replace(/\)/g, '%29') +; </script>


NOTE: I don't think these solutions are elegant, but I believe they are the only way to solve your problem.

Scroll to Top