Search code examples
media-queriespolymer

Polymer 1.0 dom-if does not recalculate when previously true


I have the following component that displays a specific image based on a media query. What I'm expecting to see is when the window is resized, that a different image will be loaded and displayed, and all other sizes "hidden".

What I'm getting though, is that the new image is indeed loading, but old images are not hidden. They remain visible. If I refresh the page, then the correct image is displayed. is it the iron-media-query that is not updating it's property correctly, or is it the template[dom-if] tags that isn't updating accordingly.

<dom-module id="app-image">
    <!-- Should select correct image based on size -->
    <style>
        :host {
            display: inline-block;
            position: relative;
            overflow: hidden;
        }
        :host > ::content img { display: block; }
    </style>
    <template>
        <iron-media-query query="(max-width: 421px)"
                        query-matches="{{isTiny}}"></iron-media-query>
        <iron-media-query query="(min-width: 422px) and (max-width: 641px)"
                        query-matches="{{isSmall}}"></iron-media-query>
        <iron-media-query query="(min-width: 642px) and (max-width: 1201px)"
                        query-matches="{{isMedium}}"></iron-media-query>
        <iron-media-query query="(min-width: 1202px)"
                        query-matches="{{isLarge}}"></iron-media-query>

        <template is="dom-if" if="{{isTiny}}">
            <content select="[tiny]"></content>
        </template>

        <template is="dom-if" if="{{isSmall}}">
            <content select="[small]"></content>
        </template>

        <template is="dom-if" if="{{isMedium}}">
            <content select="[medium]"></content>
        </template>

        <template is="dom-if" if="{{isLarge}}">
            <content select="[large]"></content>
        </template>

    </template>
</dom-module>
<script>
    Polymer({
        is: "app-image"
    });
</script>

And here is some sample code of this tag in use:

<app-image>
    <img tiny src="http://lorempixel.com/200/100/abstract/" />
    <img small src="http://lorempixel.com/300/150/food/" />
    <img medium src="http://lorempixel.com/600/300/animals/" />
    <img large src="http://lorempixel.com/800/400/city/" />
</app-image>

Solution

  • Ok this was answered in a github issue I logged, and turns out there is indeed a way to tell the template it needs to "re-stamp" itself.

    <template is="dom-if" if="{{active}}" restamp="true">
        <content></content>
    </template>
    

    It's actually very clearly documented [1]; I guess I was reading over the docs too fast just looking for the code snippets, rather than properly understanding the element.

    [1] https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-if