4

I am from angular, react background getting started with polymer.

I have a polymer class lets say myClass having this template.

<div  id="[[x]]">

Here x is property defined in property getter.

  static get properties() {
    return {      
      x: {
        type: Number,
        value: 200
      },
}

Here if I set value of x dynamically using chrome dev tools console, like myClass.x = '5' it works fine and output will be.

<div  id="5">

same goes true for other html attributes like

   <div  width="[[x]]">
   <div  height="[[x]]">

but now consider a case scenario that I want to give margin property dynamically to my div in the same way that I am doing with id, width, height how can I do it in Polymer?

In angular we can do this.

<div [style.marginTop.px]="marginTop">

Let me know your thought in polmer way od doing things.

Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53

2 Answers2

2

I got it, can be achieved by doing something like this.

<div style$="margin:{{ x }}px;">
Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53
  • Any insights on how to write if condition inside style$="margin:{{ if ? do this: else this }}px;" something like this? – Divyanshu Rawat Sep 12 '19 at 14:18
  • Look into computed properties if you sometimes want the value of `x` to be different. – abraham Sep 12 '19 at 21:06
  • @abraham didn't get you what I am asking is like is there any way we can write expression inside style$, in the similar way like we do in angular like this ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''blue"}" – Divyanshu Rawat Sep 12 '19 at 21:24
  • 1
    The answer is don't do it that way. Use a computed property. Use `
    ` but then compute `x` to the result of your logic.
    – abraham Sep 13 '19 at 01:23
1

It can also be achieved using CSS variables:

:root {
    --custom-margin-top: 20px;
}

div {
    margin-top: var(--custom-margin-top);
}

And via JS you can:

updateMarginTop(marginTop) {
    this.updateStyles({
        '--custom-margin-top': `{marginTop}px`
    });
}
lvilasboas
  • 76
  • 1
  • 6