style not applied to dynamic content in polymer we

2019-08-11 07:21发布

问题:

I recreate an h2-element here:

<link rel="import" href="../../js/lib/polymer/polymer.html">
    <dom-module id="x-custom">
    <style>
        h2 { color: green; }
    </style>
    <template>
        <div id="content">
            <h2>TEST</h2>
        </div>
    </template>

    <script>
    (function() {
        Polymer({
            is: 'x-custom',
            ready: function() {
                this.$.content.innerHTML = '<h2>TEST 2</h2>';
                this.updateStyles();
            }
        });
    })();
    </script>
</dom-module>

If I skip the ready-function "TEST" is green, but not "TEST 2". Thought updateStyles() may fix this, but didn't. Any ideas why this doesn't work? (Polymer 1.0, Chrome 44)

回答1:

You can't use innerHTML as usual, you need to do this with Polymers own DOM API. This works:

Polymer.dom(this.$.content).innerHTML = '<h2>TEST 2</h2>';


回答2:

How about of binding data?

<dom-module id="x-custom">
<style>
    h2 { color: green; }
</style>
<template>
    <div id="content">
        <h2>{{test}}</h2><!-- this will be in green color -->
    </div>
</template>

<script>
(function() {
    Polymer({
        is: 'x-custom',
         properties:{
          test:{
            type:String,
            value:"test 1"
          },
         },
        ready: function() {
          this.test = "test 2"
        }
    });
})();
</script>