north
north

Reputation: 605

dom-if issue with Polymer 1.x

I have a couple of conditionally stamped elements inside a template repeater. Now when I update the data, the if-conditions don't seem to take effect, which results in undefined getting passed into the functions which handle the data for those elements.

Using the restamp property didn't seem to help (https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-if). So far I was only able to solve this by emptying the items property (this.items = [];) inside my change handler which initiates a new request.

This works, but results in the template being empty for a short amount of time before the new data gets displayed. Not necessarily a problem, but I wonder if I'm doing something wrong.

Here are the corresponding 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();
    }
  }
...

Upvotes: 3

Views: 5760

Answers (2)

Scott Miles
Scott Miles

Reputation: 11027

Given "{{item.info.subtitle}}", if item.info is null or undefined or if item.info.subtitle is undefined, the binding will not refresh and may have a stale value (in the context of a repeat where nodes are re-used).

Polymer doesn't perform calculations on undefined values because it's a performance enhancement in a large number of cases, however it can be tricky in this scenario.

You should use a function to resolve the correct state. Something like

if="{{hasSubtitle(item)}}"

and

hasSubtitle function(item) {
  return item.info && item.info.subtitle;
}

Upvotes: 4

sam_dw
sam_dw

Reputation: 159

The "if" property of "dom-if" requires a Boolean.

Try creating a polymer property that will be set to true or false if "item.info.subtitle" is not empty or null.

Then use the created property with dom-if:

<template is="dom-if" if="{{hasSubtitle}}" >

reference: http://polymer.github.io/polymer/ --> dom-if (dropdown)


Additional info: Added on June 10th

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.
        }
    },
    ...
});

Upvotes: 0

Related Questions