How to set CSS style in Polymer 3 using JS functions

337 Views Asked by At

So, I am fairly new to Polymer but I have worked trough all tutorials I could find and the search function doesn't help me with my problem either.

I am trying to set the style of elements via JS functions. I know that I could use things like:

getColor () {
  if(this.is_even) {
    return  "background-color: green;";
  }
  else {
    return "background-color: red;";
  }
}

static get template() {
  return html`
    <div class="icon" style$="[[getColor()]]"></div>
  `
}

To set my icon's background color depending on its "is_even" property. My question is: Can I do this in css style tags too? Is there an equivilant syntax like this:

.icon
{
  $[[getColor()]]
}

or maybe

.icon
{
  background-color$: [[getColor()]];
}

I am trying to edit the style of my ":host" element depending on certain conditions via this kind of syntax and I can't find anything about it.

Thanks in advance :)

1

There are 1 best solutions below

1
On BEST ANSWER

Here a sample how to do with css :

DEMO

static get template() {
return html`
  <style> 
  .cfalse {
    background-color: red;
  }

  .ctrue {
    background-color: green;
  }
  </style>

  <div class$="icon c[[is_even]]"></div>
`;
}

You may do it with observer :

static get observers() {
  return [
    'checkColor(is_even)'
  ]
}

checkColor(e) {
  this.set('getColor', !!e ? "background-color: green;" : "background-color: red;" );

  }

static get template() {
  return html`
    <div class="icon" style$="[[getColor]]"></div>` }

Or you may set observer at property decleration :

static get properties() {
    return {
      is_even: {
        type: Boolean,
        // Observer method identified by name
        observer: 'checkColor'
      }
    }
  } 

EDIT : Also it is possible to render the html style with Polymer Lit Element's advantage. In order to use lit element

import { LitElement, html } from '@polymer/lit-element'; 

then after extend your custom element lit Element's class :

class MyElement extends LitElement {
  static get properties(){.....
 ....

Then finally:

${this.is_even?
  html`<div class="icon" style="background-color: green;"></div>`:
  html`<div class="icon" style="background-color: red;"></div>`}

For more about litElement