polymer-2.xdom-repeatpolymer-2.0

Polymer2.0 - is it possible to set default value in dom-repeat?


I am trying to set the default value in dom-repeat.

In below example, I am trying to display default image(http://img04.deviantart.net/8465/i/2009/260/f/a/blender__texture_dummy_by_3d_asuarus.jpg) in dom repeat if the image is not available or undefined

I think , we cant use doublepipe operator in the expression [[item.image]]

HTML:

<head>
  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
</head>

<body>
<x-custom></x-custom>
<dom-module id="x-custom">
  <template>
    <style>
      .test{
  display:inline;
  float:left;
  border:1px solid black;
  margin:5px;
  padding:5px;
  text-align:center;
}
    </style>
    <div> Employee list: </div>
    <template is="dom-repeat" items="{{employees}}">
      <div class="test">
        <div># [[index]]</div>
        <div>First name: <span>[[item.first]]</span></div>
        <div>Last name: <span>[[item.last]]</span></div>
        <div><img src="[[item.image]]" width="50px"></div>
      </div>  
    </template>

  </template>

</dom-module>

JS:

   class XCustom extends Polymer.Element {

      static get is() { return 'x-custom'; }

      static get properties() {
        return {
          employees: {
            type: Array,
            value() {
              return [
                {first: 'Bob', last: 'Smith',image:'https://dummyimage.com/300.png/09f/fff'},
                {first: 'Adam', last: 'Gilchrist',image:'https://cdn.pixabay.com/photo/2015/03/04/22/35/head-659652_960_720.png'},
                {first: 'Sally', last: 'Johnson'},
              ];
            }
          }
        }
      }

    }

    customElements.define(XCustom.is, XCustom);

Codepen- https://codepen.io/nagasai/pen/EvPdLB


Solution

  • No, we cannot use pipe operator. But:

    1. If you are just after setting a default value for image if not found or null:

      <object data="[[item.image]]" type="image/png" width="50px"> <img src="http://img04.deviantart.net/8465/i/2009/260/f/a/blender__texture_dummy_by_3d_asuarus.jpg" width="50px"/> </object>

    More at: Inputting a default image in case the src attribute of an html <img> is not valid?

    1. For other items you can use <dom-if>:

      <span> <template is="dom-if" if="[[!item.first]]">DefaultValue </template> [[item.first]] </span>

    I hope this helps.