javascripthtmlpolymerdom-repeat

in Polymer how do I make a list of elements using <template is="dom-repeat"> with values and a button to delete itself?


I use to display every object in an Array on a paper-card. But I also want to be able to have a paper-button next to every object that deletes the object from the Array once you press it. (This is all inside a custom element) I haven't been able to achieve this with the following code:

my-element.js:

<template is="dom-repeat" items="{{items}}" as="item">
    <paper-card>
        <div>Item [[item.number]]
        <paper-button on-click="deleteItem">delete</paper-button></div>
    </paper-card>
</template>
deleteItem(o) {
    const item = o.model.item;
    this.tafels = this.tafels.filter(function(e) {
        return e !== item;
    });
}

I've also tried using an anonymous inline function like this:

<template is="dom-repeat" items="{{items}}" as="item">
    <paper-card>
        <div>Item [[item.number]]
        <paper-button on-click="(function(){console.log('deleted')})();">delete</paper-button></div>
    </paper-card>
</template>

But that didn't work either. Am I doing something wrong or are these not valid options to achieve what I'm looking for?


Solution

  • You try to compare elements, which is generally not the best practice. Try deleting them based on a unique id/number, eg:

    <paper-button on-click="deleteItem" unique-id=[[item.id]]>delete</paper-button>
    
    deleteItem(o) {
        this.tafels = this.tafels.filter(function(e) {
            return e.uniqueId !== o.currentElement.uniqueId;
        });
    }
    

    Next to that you appear to be using 'items' as input for your dom-repeat, while using 'tafels' when editing. These two should be the same.