FrancescoM
FrancescoM

Reputation: 1400

Saving page state to current route as parameter

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

Answers (2)

Matt
Matt

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

Sam Herrmann
Sam Herrmann

Reputation: 6976

I have updated your StackBlitz example here.

Here are the key steps:

  1. Import the Angular RouterModule into your app:

    @NgModule({
      imports: [
         RouterModule.forRoot([])
       ]
     })
     export class AppModule {}
    
  2. 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;
         }
      });
    }
    
  3. 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

Related Questions