Dom-if problem with Polymer 1.x
I have several conditionally stamped elements inside a template repeater. Now when I update the data, the if conditions don't take effect, which results in what gets undefined
passed to the functions that process the data for those elements.
Using the property restamp
didn't help ( https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-if ). So far, I could work it out by omitting the items ( this.items = [];
) property inside my change handler, which will initiate a new request.
This works, but it causes the template to remain empty for a short amount of time before new data is displayed. Not necessarily a problem, but I'm wondering if I'm doing something wrong.
Here are the relevant parts of the code:
<template>
...
<iron-ajax
id="ironajax"
url="https://www.url.com/api"
params="{{ajaxParams}}"
handle-as="json"
on-response="handleResponse"
on-error="handleError">
</iron-ajax>
...
<template is="dom-repeat" items="{{items}}" id="items">
...
<template is="dom-if" if="{{item.info.subtitle}}">:
<span>{{truncateSubtitle(item.info.subtitle)}}</span
</template>
...
Polymer({
is: 'my-element',
properties: {
query: {
type: String,
value: ''
}
...
items: {
type: Array,
value: []
}
}
...
handleChange: function() {
if (this.value !== '') {
this.items = [];
this.query = this.value;
this.$.ironajax.generateRequest();
}
}
...
source to share
Given "{{item.info.subtitle}}"
if item.info
- null
or undefined
, or if item.info.subtitle
- undefined
, the binding will not update and may be deprecated (in a retry context where nodes are reused).
The polymer does not compute by value undefined
because it improves performance in a large number of cases, but in this case it can be difficult.
You must use a function to resolve the correct state. Something like
if="{{hasSubtitle(item)}}"
and
hasSubtitle function(item) {
return item.info && item.info.subtitle;
}
source to share
The "if" property for "dom-if" requires a boolean.
Try to create a polymer property that will be set to true or false if "item.info.subtitle" is not empty or null.
Then use the generated property with dom-if:
<template is="dom-if" if="{{hasSubtitle}}" >
link: http://polymer.github.io/polymer/ -> dom-if (dropdown menu)
Additional information: Added June 10
Try using a property instead of a method.
Declare your property like this:
Polymer({
is: "my-element",
properties: {
hasSubtitle: {
type: Boolean,
value: 'false', //false or true, the more common case.
}
},
...
});
source to share