I have angular 5 basic beginner level app there are just 5 components
my routing and links look like this
//copied from app.module.ts
const appRoutes:Routes = [
{path:'',component:HomeComponent},
{path:'items/:cat',component:ItemsComponent},
{path:'itemdetail/:id',component:ItemdetailComponent},
{path:'settings',component:SettingsComponent},
];
//copied from navbar.component.html
<ul>
<li><a [routerLink]="['/']">Home</a></li>
<li><a [routerLink]="['/items/8']">Rashion</a></li>
<li><a [routerLink]="['/items/2']">Vegitables</a></li>
<li><a [routerLink]="['/items/3']">Fruits</a></li>
<li><a [routerLink]="['/items/7']">Other</a></li>
<li><a [routerLink]="['/items/5']">Sweets</a></li>
<li><a [routerLink]="['/settings']">Settings</a></li>
</ul>
//copied from items.component.ts
ngOnInit(){
this.cat = this.route.snapshot.params['cat'];
this.itemsSrv.getItems(this.cat)
.subscribe((data)=>{
this.items=data;
});
}
links only work if it is going to different component,
means I can navigate from home page to /items/2
but when I am in items component I can navigate to /items/any-parameter
although from Items i can go to home or settings component.
in short it is now working to navigate to same component even if parameter is different.
I noticed one thing, URL is getting changed but page content is same as old page not reloading new url :(
Angular does not reload components by default when route parameters change if the route itself stays the same. This is particular problem when, say for example, you have a list of products on a page e.g. /product/:id. Switching between products will keep the route, /product/, the same but just update the id.
The first approach is to tell the Angular router to emit the route events on refresh and then handle them accordingly in our routed component. In early Angular versions, there was no option to tell the router to emit events on same route refresh. Angular 5.1 introduced the onSameUrlNavigation property on the routers ExtraOptions.
2 or more route declarations point to the same component. If a different route matches to the same component, the DOM and component are thrown away. I should be able to change my route to anything and as long as it results in the same component being in the same routerOutlet, it should stay around.
If a different route matches to the same component, the DOM and component are thrown away. I should be able to change my route to anything and as long as it results in the same component being in the same routerOutlet, it should stay around. This is in reference to some comments in #9811
So, the best way is using subscribe for route:
userSubscription: Subscription;
...
ngOnInit() {
this.userSubscription = this.route.params.subscribe(
(params: Params) => {
//------ some code -----
})
}
After that, you must to unsubscribe:
ngOnDestroy(): void {
this.userSubscription.unsubscribe()
}
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