Reputation: 1400
Any clue on how to keep sincronized some information about the state of a particular page directly in the url as a url parameter.
Considering this stackblitz
I would like that every time the food is selected the url is updated with param ?favouriteFood=selectedFood
Of course such params, if present, will be used on the ngInit() to initialize the state of the page.
Upvotes: 1
Views: 709
Reputation: 35251
Try using replaceState
.
import {Location} from '@angular/common';
@Component({
selector: 'example-component',
templateUrl: 'example.component.html'
})
export class ExampleComponent
{
constructor( private location: Location )
{}
setTheFood()
{
this.location.replaceState('favouriteFood=selectedFood');
}
}
Upvotes: 0
Reputation: 6976
I have updated your StackBlitz example here.
Here are the key steps:
Import the Angular RouterModule into your app:
@NgModule({
imports: [
RouterModule.forRoot([])
]
})
export class AppModule {}
Listen to route query parameter changes from the ActivatedRoute:
ngOnInit() {
// Remember to unsubscribe when this component is destroyed
this.route.queryParams.subscribe(params => {
const selectedFood = this.foods.find(f => f.value === params.food);
if (selectedFood) {
this.selectedFood = selectedFood;
}
});
}
Update the URL when the user changes the selection from the available choices using Router.navigate:
foodSelectionChange(change: MatSelectChange) {
const food: Food = change.value;
this.router.navigate([], {
queryParams: { food: food.value }
});
}
Upvotes: 1