Adding dynamic css class using lit-html

2,270 views
Skip to first unread message

Ronn Ross

unread,
Feb 19, 2018, 8:19:31 AM2/19/18
to Polymer
I'm attempting to dynamically apply a css class using a property. For example I want to pass in a string:

<my-button kind="primary">some stuff</my-button>

My component looks like so: 

class MyButton extends LitElement {
static get properties() {
return {
kind: String
}
}

constructor() {
super();
}

render({ kind }) {
return html`
<style>
.primary {
color: red;
}
</style>
<button on-click="${() => console.log('working')}"
class="${kind}"
type="button">
Press Me!
</button>
`
}
}

When I hard-code the class on the element it works. Any ideas? 

Thanks!

Justin Fagnani

unread,
Feb 19, 2018, 12:01:32 PM2/19/18
to Ronn Ross, Polymer
Neither lit-html or LitElement really help here yet, because the host element is not under control of its own template.

Right now using className or classList in render() is the best option.

render() {
  this.className = this.kind;
}

or if you have other classes you need to not disturb:

const kinds = ['primary', 'secondary'];
render() {
  kinds.forEach((k) => this.classList.toggle(k, this.kind === k));
}


Follow Polymer on Google+: plus.google.com/107187849809354688692
---
You received this message because you are subscribed to the Google Groups "Polymer" group.
To unsubscribe from this group and stop receiving emails from it, send an email to polymer-dev+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/polymer-dev/8f731c01-2f4d-470a-ac21-804d15050957%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages