ngx-advanced-router
v2.0.0
Published
A better way to handle Angular routes
Downloads
16
Maintainers
Readme
ngx-advanced-router
Example
Usage
- Install the package:
npm install --save ngx-advanced-router
- Create a service that extends
AdvancedRouteService
. This is where you'll supply your routes.
While the default Angular router only allows paths to be supplied as strings,ngx-advanced-router
allows paths to be supplied as either strings OR or functions.
// ...
import { AdvancedRouteService } from 'ngx-advanced-router';
@Injectable({
providedIn: 'root',
})
export class YourAdvancedRouteService extends AdvancedRouteService {
public readonly routesConfig = {
somePath: {
path: 'some-path', // Regular string path
component: SomeComponent,
},
someDetailPath: {
path: (id: string) => `some-path/${id}`, // Function-generated string path
component: SomeDetailComponent,
}
// ...
fallBack: {
path: '**',
redirectTo: 'some-path',
},
};
}
- Import the
AdvancedRouteModule
into yourAppModule
(orAppRoutingModule
) using theforRoot()
method, and pass in your advanced route service class.\
// ...
import { AdvancedRouterModule } from 'ngx-advanced-router';
import { RouterModule } from '@angular/router';
import { YourAdvancedRouteService } from './services/your-advanced-route.service';
@NgModule({
// ...
imports: [
AdvancedRouterModule.forRoot(YourAdvancedRouteService),
],
})
export class AppModule {} // or AppRoutingModule
- Import the route service into any places where you need to access route paths.
// ...
import { YourAdvancedRouteService } from './services/your-advanced-route.service';
import { LazyLoadedRouteService } from './modules/lazy-loaded/services/lazy-loaded-route.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor(
// ...
protected yourAdvancedRouteService: YourAdvancedRouteService,
private router: Router,
) {}
// ...
}
You can then use it inside a function:
navigateToSomePath(): void {
const somePath = this.yourAdvancedRouteService.routes.somePath.path;
this.router.navigate([somePath]);
}
Or in a routerLink in the HTML:
<a [routerLink]="yourAdvancedRouteService.routes.somePath.path">
License
MIT