aurelia Custom Elements Creating A Custom Element With Bindable Properties

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Creating a Custom Element with bindable properties is a snap. If you want to create an element that accepts one or more values which the plugin can use, the @bindable decorator and syntax is what you are looking for.

Below, we are creating a custom element that accepts an array of fruits and displays them.

Example: my-element.js

import {bindable} from 'aurelia-framework';

const validFruits = [
    'Apple', 
    'Banana', 
    'Orange', 
    'Pineapple', 
    'Grapes', 
    'Peach',
    'Plum',
    'Dates',
    'Strawberries'
];

export class FruitCustomElement {
    @bindable fruits = [];

    fruitsChanged(newVal, oldVal) {
        if (newVal) {
            newVal.filter(fruit => {
                return validFruits.indexOf(fruit) >= 0;
            });
        }
    }
}
<template>
    <ul if.bind="fruits">
        <li repeat.for="fruit of fruits">${fruit}</li>
    </ul>
</template>

Using it:

export class MyViewModel {
    myFruits = [];

    attached() {
        this.myFruits = ['Apple', 'Banana', 'Orange', 'Pineapple', 'Grapes', 'Peach'];
    }
}
<template>
    <require from="./my-element"></require>

    <fruit fruits.bind="myFruits"></fruit>
</template>


Got any aurelia Question?