DecafJava
DecafJava

Reputation: 479

How can I dynamically include stylesheets to apply to Polymer 2 element?

I have a custom Polymer 2 video-player element and I want the ability to pass in a property to each element instance in order to define which stylesheet to apply to it (different theme names are released each year and each set of styles currently exist on the server in their own file which has a predictable naming format). I saw some examples with inline tags, but that seems to only be an acceptable solution for smaller styles (otherwise it gets out of control for me to jam all my styles in there, which there are a lot of). How can I do the theme-ing properly?

Here's what I got so far in two separate HTML files:

Demo File (demo-page.html)

<link rel="import" href="../my-video-player.html">
<my-video-player data="{...}" theme="2016"></my-video-player>
<my-video-player data="{...}" theme="2017"></my-video-player>

Component File (my-video-player.html)

<dom-module id="my-video-player">
    <template>
        <link type="css" rel="import" href="css/[[theme]]/styles.css">
    </template>
    <script>
        class MyVideoPlayer extends Polymer.Element {
            ...
        }
    </script>
</dom-module>

Note: I tried putting the above link tag one level outside of the template tag as well, but that didn't work.

Right now what happens is only one of the two theme stylesheets get applied to both of my components. What I need instead is for the first component to get the 2016.css stylesheet applied to it, while the second gets the 2017.css stylesheet.

Upvotes: 2

Views: 222

Answers (1)

Evan Bechtol
Evan Bechtol

Reputation: 2865

To add external stylesheets, you need to create a custom component that contains all the styles you want. Then, you can link the "style" component into the component(s) using the styles like this:

<link rel="import" href="/shared-styles.html">

<dom-module id="sus-app">
  <template>
    <style include="shared-styles"></style>
    <style>
      neon-animated-pages {
        height: 500px;
      }

      neon-animatable {
        padding-top: 2em;
         padding-left: 10em;
         padding-right: 10em;
      }

Notice that you can still include styles unique to the component that she shared styles are being used with.

Upvotes: 1

Related Questions