EmberJS – Router Sticky Query Param Values

In Ember, the query parameter values are sticky by default; in a way that any changes made to the query parameter, the new value of query parameter will be preserved by reentering the route.

Syntax

Ember.Controller.extend ({
   queryParams: ['paramValue'],
   paramValue:true/false
});

Example

The example given below specifies the use of sticky query parameter values. Create a new route and name it as stickyqueryparam and open the router.js file to define the URL mappings −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('stickyqueryparam');
});

//It specifies Router variable available to other parts of the app
export default Router;

Open the file application.hbs created under app/templates/ with the following code −

<h2>Sticky Query Param Values</h2>
{{#link-to 'stickyqueryparam'}}Click here to open the page{{/link-to}}

When you click the above link, it opens the sticky query parameter template page. The stickyqueryparam.hbs file contains the following code −

<h2>My Page</h2>
{{link-to 'Show' (query-params showThing=true)}}
{{link-to 'Hide' (query-params showThing=false)}}
<br>
{{#if showThing}}
   <b>Welcome to Adglob..</b>
{{/if}}
{{outlet}}

Now open the stickyqueryparam.js file created under app/controllers/ with the below code −

import Ember from 'ember';

export default Ember.Controller.extend ({
   queryParams: ['showThing'],
   //showThing would be false, if only the route's model is changing
   showThing: false
});

Output

Run the ember server and you will receive the following output −

When you click on the link, it will open the sticky query param template page by providing Show and Hide links −

sticky by default

When you click on the Show link, it will display the text and Hide link hides the text −

Previous Page:-Click Here

Leave a Reply