Brombomb
Brombomb

Reputation: 7076

Overriding styles from an element atrribute

I am trying to create a polymer component that can be style by changing it's attributes.

My base component looks like:

  <dom-module id="item">
  <template>
      <style>

          #item {
              display: border-box;
              line-height: 1rem;
              color: var(--boxcolor, #345d83);
              margin: 10px;
              border-radius: 4px;
              border-top: 1px solid transparent;
              border-right: 1px solid transparent;
              border-bottom: 1px solid transparent;
              border-left: 4px solid #f2f2f2;
          }

          #item:hover {
              background-color: #f5f9fd;
              border-left: 4px solid var(--boxcolor, #345d83);
              border-top: 1px solid #f2f2f2;
              border-right: 1px solid #f2f2f2;
              border-bottom: 1px solid #f2f2f2;
          }

          .box {
              padding: 10px;
          }

          .subtitle {
              font-size: .9rem;
          }

      </style>

      <div id="item">
          <div class="box">
              <content></content>
              <div class="subtitle">
                  <strong>{{value}}</strong> {{label}}
              </div>
          </div>
      </div>
  </template>

  <script>
      Polymer({
          is: 'item',
          properties: {
              value: String,
              label: String,
              boxcolor: String
          }
      });
  </script>

What I am trying to do is use this element as such:

<item value="5x" label="cooler than Hello!" boxcolor="#f00">My World now!</item>

Upvotes: 1

Views: 101

Answers (1)

Srik
Srik

Reputation: 2381

There are different approach to make this work. My recommendation would be to use custom property api described in below link.

https://www.polymer-project.org/1.0/docs/devguide/styling.html#style-api

Basically you need to update your custom style variable --boxcolor whenever the attribute boxcolor changes. Below is the updated script.

<script>
  Polymer({
      is: 'item',
      properties: {
          value: String,
          label: String,
          boxcolor: {
            type: String,
            observer: '_boxColorChange'
          }
      },
      _boxColorChange: function(newValue) {
        this.customStyle['--boxcolor'] = newValue;
        this.updateStyles();
      }
  });
</script>

Update: Looks like there is a custom style variable defined in the original code. I missed that part. I have updated the code to update the custom style variable available in the original code.

Upvotes: 3

Related Questions