I'm trying to directly bind an array to a Polymer 2 component template. It works at first but then it doesn't detect changes. I'm using this.push
method in order to allow Polymer to detect the changes, but it's not working. Binding to a dom-repeat
template it's OK.
Here you can find a Plunker: http://plnkr.co/edit/MWO7i7m3GB5b7Eqri1yX?p=preview
Is it possible to do what I'm trying? What am I doing wrong?
Thank you for your help
No it's not possible to bind to an array like this.
[[json(data)]]
if data is an array, it won't work.
The same way for the observers :
static get observers(){
return [
'_dataChanged(data)'
]
}
This won't work.
On a direct binding, the only way for it to work is to change the complete array value with another one.
class ParentElement extends Polymer.Element {
static get is() { return "parent-element"; }
static get properties(){
return {
data: {
type: Array,
notify: true,
value: function(){
return [{name: 'first'}]
}
}
}
}
constructor() {
super();
}
json(data){
return JSON.stringify(data);
}
addChild(){
this.data = [{name: 'first'},{name: 'second'}];
}
}
customElements.define(ParentElement.is, ParentElement);
In this case above, you can see that the data
array is completely replaced and it will work because it's the data
object that changed.
In your case you change the content of the array, then the binding won't work.
If you want to see something, in you plunker you can change the HTML part with :
[[json(data.*)]]
Then you will see the polymer binding object that changed. But instead of binding an array like you did, the best is to use an observer and do our action in the function :
static get observers(){
return [
'_dataChanged(data.splices)'
]
}
_dataChanged(value){
//work to do here
}
For more details you can check the polymer doc here