aureliabindable

How to pass route param as bindable value to component's viewmodel (not view)


I have used route navigation where I access route params from activate.

app.ts

export class App {
   configureRouter(config) {
    config.map([
        { route: 'student/:id', name: 'student', moduleId: 'student',  nav: true, title: 'student', href: '#' }
    ]);
}

}

student.ts

export class Student {
    id;

activate(params) {
    this.id = params.id;
   }
}

The page it routes to is built using several components that need this parameter to be passed.

<template>
    <require from="grade" > </require>
    <h1> Student - ${id} </h1>
    <grade id.bind="id"></grade>
    <department id.bind="id"></department>
<template>

In my grade view, it gets the id correctly when I display it in an html element (after I make it a bindable in viewmodel):

grade.html <span>${id}</span>

But, I cannot get the id in the viewmodel of grade i.e. grade.ts

    export class Grade{
      @bindable id;
        constructor() {
          console.log("id=", this.id};
 }

comes up as undefined. I tried to access it via activate as I did in student but looks like templates are not activated when the page loads. I think the issue is not with the routing, but how to access bindable values in viewmodel in general. I tried one-time and two-way bindingmodes as well and they gave same results.


Solution

  • The reason it's undefined is because you're calling it in the constructor. The bindable variable is filled in the attached phase.

    If you try calling it in an attached method like this:

    attached() {
       console.log("id=" + this.id);
     }
    

    It should be filled.

    For more information on Aurelia Component Lifecycles, click here