Dac0d3r
Dac0d3r

Reputation: 1854

How to set a parent property from within a custom element in Aurelia?

A few days ago I asked this question 2 way databinding in Aurelia custom elements - bind custom element to parent viewmodel

Now I need to be able to reuse the allSelectableValues from my custom element (my-custom.js) in my parent element (create.js).

I need this for a custom value converter I have on create.js which contains some Ids which I need to display names for instead, by looping through the array of elements, currently fetched and residing in my custom element.

**create.html**
<td>${d.SomeID | allSelectableValuesMapping}</td>

and

**value-converters/all-selectable-values-mapping.js**
export class AllSelectableValuesMappingValueConverter {
    toView(value) {
        for(let item in allSelectableValues) {
            if (item.SomeID == value){
                return item.Name;
            }
        }

    }
}

In the ideal world I'd have hoped something like this would have worked:

**my-custom.js**
async attached() {
    this.allSelectableValues= await await this.myService.getAllValues();
    this.parent.allSelectableValues = this.allSelectableValues;
}

But my custom element have no idea of the parent which is requiring it.

Does anyone have an idea how to set the parent's allSelectableValues equal to the custom element's allSelectableValues from within the custom element? Or is there another, better way of achieving it, while still maintaining the two-way databound custom element?

Upvotes: 1

Views: 1087

Answers (1)

Zhang
Zhang

Reputation: 11607

Something like this ?

Please take extra note of the @customElement('CustomElement') declarator above the export class CustomElement line of code.

Custom Element View Model

import {inject} from 'aurelia-framework';
import {customElement} from 'aurelia-framework';
import {bindable} from 'aurelia-framework';

@customElement('CustomElement')
export class CustomElement {
    @bindable arrItems
}

Custom Element HTML

<template>
    <div repeat.for="item of arrItems">$(item.someProperty}</div>
</template>

Parent View Model

export class ParentViewModel {
    parentArrItems = [];
}

Parent HTML

<template>
    <require from="customelement"></require>

    <CustomElement arrItems.bind="parentArrItems"></CustomElement>
</template>

Upvotes: 1

Related Questions