For problems like 'angular router optional parameter', 'angular route component reuse':
UrlMatcher is for creating a custom route matcher for a route pattern (which leads to your desired component). As a result, a customized route pattern is going to be handled, and the corresponding requests are handled by that component.
In the routes array,
{ matcher: productsMatcher, component: ProductsListComponent}
is a route, just as { path: 'somewhere', component: SomeComponent }
that defines a route.
A matcher takes the whole url string as an array of segments. The segments can be assigned to route params, which can be read by the component.
import { RouterModule, Routes, UrlMatchResult, UrlSegment } from '@angular/router';
const productsMatcher = (segments: UrlSegment[]): UrlMatchResult => {
if (segments.length === 1 && segments[0].path === 'products') {
return {
consumed: segments,
posParams: {}
}
}
if (segments.length === 2 && segments[0].path === 'products') {
return {
consumed: segments,
posParams: {
category: segments[1]
}
}
}
return <UrlMatchResult>(null as any);
}
const routes: Routes = [
// { path: '/products', component: ProductsListComponent },
// { path: '/products/:category', component: ProductsListComponent },
{ matcher: productsMatcher, component: ProductsListComponent},
];
angular doc
In your component
ngOnInit(): void {
this.route.paramMap.subscribe(param => {
const category = param.get('category')
if (category) { this.loadStuff(category) }
})
}
All requests of the same url pattern are directed to this component.
As a result, (after it is created at the first request) there are no redraws/recreation of the ProductsListComponent. Thus there's no flickering when visiting /products/:category
route from /products
route: angular sees it as the same route, so the component won't reload.
For reference 1 2