Using Conditional slot in polymer

Viewed 836

I was building a material design card element in polymer 3 es6 and wanted to only have <slot> tags when the attribute is set true. This is my js code:

export class ACard extends PolymerElement {
  static get is() { return 'a-card' }
  static get template() { return `


<div class="card">
  <script>
      if ([[media]]) {
          <div class$="card-image">
            <slot name="image"></slot>
          </div>
      };
  </script>
  <div class="card-stacked">
    <div class="card-content">
      <slot name="title" class="card-title"></slot>
      <slot name="text"></slot>
    </div>
    <div class$="card-action">
      <slot name="action-link"></slot>
    </div>
  </div>
</div>`


  }
  constructor() {
    super();
  }
  static get properties() {
    return {
      media: {
        type: Boolean
      }
    }

  }
}

customElements.define(ACard.is, ACard)

This is my index.html:

<a-card media="true">
  <img slot="image" src="">
</a-card>

So when media attribute is set to true card-image div and slot inside it is returned. Have to apologize because I'm new to javascript and may have serious syntax and logical issues in the example.

1 Answers

Use Dom-if template

<a-card media="true">
  <template is="dom-if" if="{{media}}">
    <img slot="image" src=""/>
  </template>
</a-card>

image will display only when

media=true

Related