简体   繁体   中英

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:

  • Using dom-if but it would add crap to my resulting HTML.
  • Is there a dom-switch ? If it were something like that and didn't leave empty template tags (as it would do with dom-if ) it would be nice.
  • It's possible to load a component dynamically? Using something like this: <[[item.type]] item-configuration=[[item.configuration]]></[[item.type]]>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM