In my application I like to create a master (CRUD) for physician. I have a physician component for creating, editing and listing. A separate component for viewing it. I would like to URL's like
physician/create
physician/list
physician/edit/3
So I created route with children
const routes: Routes = [
{
path: 'physician',
children: [
{ path: 'list', component: PhysicianComponent },
{ path: 'create', component: PhysicianComponent },
{ path: 'update/:id', component: PhysicianComponent },
{ path: 'view/:id', component: PhysicianViewComponent }
]
}
For create, update and list I want to use the same component, but different output using some conditions inside the component class
Yes you can as said by @tomer above. i want to add some point to @tomer answer. firstly you need to provide name to the router-outlet where you want to load the second routing view in your view.
BaseRouteReuseStrategylink This base route reuse strategy only reuses routes when the matched router configs are identical. This prevents components from being destroyed and recreated when just the fragment or query parameters change (that is, the existing component is reused).
Each route in this array is a JavaScript object that contains two properties. The first property, path , defines the URL path for the route. The second property, component , defines the component Angular should use for the corresponding path.
Yes, by using the ActivatedRoute service and by that you check route parameters and router url to check which condition to apply but that is hard to maintain. Imagine, you just change the url or change the parameter name so you need to change that at the component. Another way is to add data property to each route something like a flag and based on that flag you apply specific conditions-
const routes: Routes = [
{
path: 'physician',
children: [
{ path: 'list', component: PhysicianComponent, data: { kind: 'list' } },
{ path: 'create', component: PhysicianComponent, data: { kind: 'create' } },
{ path: 'update/:id', component: PhysicianComponent, data: { kind: 'update' } },
{ path: 'view/:id', component: PhysicianViewComponent, date: { kind: 'view' } }
]
}
component:
ngOnInit() {
this.activeRoutedService.data.subscribe(data => {
switch (data.kind) {
//....
}
});
}
You can set route data and get the data in your component to show different output:
{ path: 'list', component: PhysicianComponent, data: { viewOption: 'list' } },
{ path: 'create', component: PhysicianComponent, data: { viewOption: 'create' } },
{ path: 'update/:id', component: PhysicianComponent, data: { viewOption: 'update' } },
In your component, get the data from ActivatedRoute.snapshot.data
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.viewOption = this.route.snapshot.data.viewOption;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With