Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value for bindable properties in Aurelia HTML only element

Tags:

aurelia

Supposed I have the following html only element:

<template bindable='value: Math.random()'>
    ${value}
</template>
<!-- In another component {Main} -->
<template>
    <require from='./that-element'></require>
    <that-element></that-element>
</template>

The result is an empty string in main component. The question is how can I define a default value for html only element?

EDIT: Default value for element will not work if an 2 bindings need to have the same unique default value. I can make it unique myself but then I have to do it manually. Was looking for something like Math.random()

like image 626
bigopon Avatar asked Oct 31 '25 17:10

bigopon


2 Answers

The contents of bindable attribute on <template> tag is handled as comma-separated list of strings. Therefore, you won't be able to set default values there.

I can think of two approaches:

  1. Set default values in parent viewmodel class and use explicit binding. Considering above scenario, this will work for you.

<that-element value.bind="someVarFromParent"></that-element>

  1. In some really simple cases, when default value should be a static string, you can use JavaScript expressions within an interpolation.

${value || 'default value'}

Gist demo: https://gist.run/?id=f0698d5b0066c3674c29c40d850217dc

like image 182
Marton Sagi Avatar answered Nov 04 '25 15:11

Marton Sagi


Just putting my 2 cents in here...I think Marton nailed it on the head with the html only solution. I generally use the value.bind method because I usually always have a vm along with my view. So, to simplify JayDi's response (which is a valid response), I've created a GistRun for you.

Basically, you'll create a custom-elem html file and a custom-elem js file. In the html file, you would have something like this:

<template>
  <h1>${value}</h1>
</template>

and in the js file, you'd have something like this:

import {bindable} from "aurelia-framework";

export class CustomElem {
  @bindable value = "default value";
}

Finally, you'd just require it in your main parent file like so:

<template>
  <require from="./custom-elem"></require>

  <custom-elem></custom-elem>
  <custom-elem value.bind="'myVal'"></custom-elem>
</template>

I just added a default value for the custom element. You can leave it undefined if you'd like. Also, you can add as many properties as you would like. This is the simplest way to tackle this in my opinion, unless your situation lets you get by with the html only method.

Also, in this case, I'm using a string of "myVal". If you wanted to use a variable that you have in your parent vm, you would just take the single quotes off and use that variable name.

Here's the running Gist so that you can fool around with it: https://gist.run/?id=2eb14ecd2b0b859fd5d1a33b5ee229bd

like image 43
Brandon Avatar answered Nov 04 '25 16:11

Brandon