Marek M.
Marek M.

Reputation: 3951

How to get route parameter in aurelia custom component

I'm creating a custom component in aureliajs framework and injecting it a Router instance:

@inject(Router)
export class Pagination {
    constructor(router) {
        this.router = router;
    }
}

It will be used with list view-models in order to setup some basic pagination. Therefore I need to read current page number from an active route (that would look like: orders/:pageNum. I'm not sure however how to do it? I mean - I know it should probably be placed in Pagination attached method, but how to get to this :pageNum param?

Upvotes: 3

Views: 3492

Answers (2)

Sylvain
Sylvain

Reputation: 19249

You can use router.currentInstruction.params and router.currentInstruction.queryParams.

You can also observe the router to be notified when the route changes:

let sub = this.bindingEngine.propertyObserver(
    this.router, 'currentInstruction').subscribe(currentInstruction => {

  console.log(currentInstruction);

});

Upvotes: 1

Fabio
Fabio

Reputation: 11990

Create a bindable property in your custom element. Take the page number from the active route and bind it to the custom element. For instance:

import { bindable } from 'aurelia-framework';

@inject(Router)
export class Pagination {

    @bindable page;

    constructor(router) {
        this.router = router;
    }
}

Usage:

<pagination page.bind="page"></pagination>

To get the page number in the active route, use the activate() hook:

activate(params) {
   this.page = params.pageNum;
}

Upvotes: 5

Related Questions