MangaPowerZero
MangaPowerZero

Reputation: 58

Polymer - Load different components dynamically

I'm a Polymer novice, but I guess what the answer will be...

Recently I came across with this issue: I got to loop through a collection of elements (using dom-repeat) and display its contents. But every element has a unique display and bindings, making it almost impossible to display each element dynamically. The ideal scenario would be to load a different component for each display type, but it looks like there is no easy way to achieve this.

Some options I have been thinking of were the following:

Any other ideas? I would really appreciate any ideas or solutions or at least a workaround for my issue.

Upvotes: 2

Views: 908

Answers (1)

Tomasz Pluskiewicz
Tomasz Pluskiewicz

Reputation: 3662

TL;DR; you can't

Polymer (and Web Components in general I guess) are best when used in a declarative way. Out-of-the-box your best solution is dynamically creating elements and adding to DOM or messy use of dom-if.

(potential) OPTION 1

I guess you could fairly easily implement a dom-switch element to work like

<template-switch switch="[[some.value]]">
  <template-case case="10">
     <element-one></element-one>
  </template-case>

  <template-case case="20">
     <element-two></element-two>
  </template>

  <template-default>
     <element-one></element-one>
  </template-default>
</dom-switch>

I wrote this off the top of my head. There are multiple ways to implement such an element. A crucial decision is whether to use <template> internally or not. In this plunk I've implemented such element without templates but simply using content distribution.

OPTION 2

There is also Polymer.Templatizer.

Faced with a similar issue of choosing element to render dynamically I created this Plunk as a proof of concept.

As you see, you extend the <template> element with custom rules, which match against a model. You then bind the matched template's nodes with the model using Polymer.Templatizer.

Thanks to Templatizer, you don't have to pollute your actual element with conditionals and still get full binding functionality.

I'm working on a more feature-complete solution. If you're interested I could move it to a separate repository and publish.

Upvotes: 2

Related Questions