This library for generating routes
$ npm install ngx-route-maker --save
Add package to NgModule imports:
import { NgxRouteMakerConfig, NgxRouteMakerModule } from 'ngx-route-maker';
const routesConfig: NgxRouteMakerConfig = {
routes: {
home: '/',
dashboard: '/dashboard',
pages: {
_path: 'pages',
page: '/{slug}',
anotherPage: '/another/{slug}'
}
}
};
@NgModule({
...
NgxRouteMakerModule.forRoot(routesConfig),
...
})
- Usage with service:
import { NgxRouteMakerService } from 'ngx-route-maker';
export class DashboardComponent {
constructor(
private routeMaker: NgxRouteMakerService
) {
}
public getUrlByString(): string {
return this.routeMaker.make('pages.page', { slug: 'new-page' });
}
public getUrlByArray(): string {
return this.routeMaker.make(['pages', 'page'], { slug: 'new-page' });
}
}
- From string:
/pages/new-page
this.routeMaker.make('pages.page', { slug: 'new-page' });
- From array:
/pages/new-page
this.routeMaker.make(['pages', 'page'], { slug: 'new-page' });
- With default route for empty result:
/home
this.routeMaker.make('fake.path', {}, '/home');
otherwise, you'll get an error for non-existent route
- From string:
/pages/new-page
<a [routerLink]="'pages.page' | makeRoute: { slug: 'new-page' }">My Link</a>
- From array:
/pages/new-page
<a [routerLink]="['pages', 'page'] | makeRoute: { slug: 'new-page' }">My Link</a>
- With default route for empty result:
/home
<a [routerLink]="'pages.page' | makeRoute: { slug: 'new-page' } : '/home'">My Link</a>
Key | Value |
---|---|
routes | NgxRouteMaker |
Key | Value |
---|---|
_path | that's prefix which will be applied for each inside route in the same depth |
[key: string] | string or NgxRouteMaker |