Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@polymer/lit-element
Advanced tools
🛠 Status: Moved to
lit-element
LitElement is currently in development. It's on the fast track to a 1.0 release, so we encourage you to use it and give us your feedback, but there are things that haven't been finalized yet and you can expect some changes.
LitElement uses lit-html to render into the
element's Shadow DOM
and adds API to help manage element properties and attributes. LitElement reacts to changes in properties
and renders declaratively using lit-html
. See the lit-html guide
for additional information on how to create templates for lit-element.
Setup properties: LitElement supports observable properties that cause the element to update. These properties can be declared in a few ways:
@property()
decorator,
if you're using a compiler that supports them, like TypeScript or Babel.properties
getter.requestUpdate(name, oldValue)
in the setter to trigger an update and use any configured property options.Properties can be given an options
argument which is an object that describes how to
process the property. This can be done either in the @property({...})
decorator or in the
object returned from the properties
getter, e.g. static get properties { return { foo: {...} }
.
Property options include:
attribute
: Indicates how and whether the property becomes an observed attribute.
If the value is false
, the property is not added to the static observedAttributes
getter.
If true
or absent, the lowercased property name is observed (e.g. fooBar
becomes foobar
).
If a string, the string value is observed (e.g attribute: 'foo-bar'
).converter
: Indicates how to convert the attribute to/from a property.
The value can be a function used for both serialization and deserialization, or it can
be an object with individual functions via the optional keys, fromAttribute
and toAttribute
.
A default converter
is used if none is provided; it supports
Boolean
, String
, Number
, Object
, and Array
.type
: Indicates the type of the property. This is used only as a hint for the
converter
to determine how to convert the attribute
to/from a property. Note, when a property changes and the converter is used
to update the attribute, the property is never updated again as a result of
the attribute changing, and vice versa.reflect
: Indicates whether the property should reflect to its associated
attribute (as determined by the attribute option). If true
, when the
property is set, the attribute which name is determined according to the
rules for the attribute
property option will be set to the value of the
property converted using the rules from the type
and converter
property options.hasChanged
: A function that indicates whether a property should be considered
changed when it is set and thus result in an update. The function should take the
newValue
and oldValue
and return true
if an update should be requested.React to changes: LitElement reacts to changes in properties and attributes by asynchronously rendering, ensuring changes are batched. This reduces overhead and maintains consistent state.
Declarative rendering LitElement uses lit-html
to declaratively describe
how an element should render. Then lit-html
ensures that updates
are fast by creating the static DOM once and smartly updating only the parts of
the DOM that change. Pass a JavaScript string to the html
tag function,
describing dynamic parts with standard JavaScript template expressions:
html`<div>Hi</div>`
html`<div>${this.disabled ? 'Off' : 'On'}</div>`
html`<x-foo .bar="${this.bar}"></x-foo>`
html`<div class="${this.color} special"></div>`
html`<input type="checkbox" ?checked=${checked}>`
html`<button @click="${this._clickHandler}"></button>`
The easiest way to try out LitElement is to use one of these online tools:
You can also copy this HTML file into a local file and run it in any browser that supports JavaScript Modules.
When you're ready to use LitElement in a project, install it via npm. To run the project in the browser, a module-compatible toolchain is required. We recommend installing the Polymer CLI and using its development server as follows.
Add LitElement to your project:
npm i @polymer/lit-element
Install the webcomponents polyfill. If you're developing a reusable package, this should be a dev dependency which you load in your tests, demos, etc.
npm i -D @webcomponents/webcomponentsjs
Create an element by extending LitElement and calling customElements.define
with your class (see the examples below).
Install the Polymer CLI:
npm i -g polymer-cli
Run the development server and open a browser pointing to its URL:
polymer serve
LitElement is published on npm using JavaScript Modules. This means it can take advantage of the standard native JavaScript module loader available in all current major browsers.
However, since LitElement uses npm convention to reference dependencies by name, a light transform to rewrite specifiers to URLs is required to get it to run in the browser. The polymer-cli's development server
polymer serve
automatically handles this transform.
Tools like WebPack and Rollup can also be used to serve and/or bundle LitElement.
LitElement
.@property
decorator to create a property (or implement a static properties
getter that returns the element's properties). (which automatically become observed attributes).render()
method and use the element's
current properties to return a lit-html
template result to render
into the element. <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
<script type="module">
import {LitElement, html} from '@polymer/lit-element';
class MyElement extends LitElement {
static get properties() {
return {
mood: {type: String}
};
}
constructor() {
super();
this.mood = 'happy';
}
render() {
return html`<style> .mood { color: green; } </style>
Web Components are <span class="mood">${this.mood}</span>!`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element mood="happy"></my-element>
render()
(protected): Implement to describe the element's DOM using lit-html
. Ideally,
the render
implementation is a pure function using only the element's current properties to describe the element template. Note, since
render()
is called by update()
, setting properties does not trigger an
update, allowing property values to be computed and validated.
shouldUpdate(changedProperties)
(protected): Implement to control if updating and rendering
should occur when property values change or requestUpdate()
is called. The changedProperties
argument is a Map with keys for the changed properties pointing to their previous values.
By default, this method always returns true
, but this can be customized as
an optimization to avoid updating work when changes occur, which should not be rendered.
performUpdate()
(protected): Implement to control the timing of an update, for example
to integrate with a scheduler. If a Promise is returned from performUpdate
it will be
awaited before finishing the update.
update(changedProperties)
(protected): This method calls render()
and then uses lit-html
in order to render the template DOM. It also updates any reflected attributes based on
property values. Setting properties inside this method will not trigger another update.
firstUpdated(changedProperties)
: (protected) Called after the element's DOM has been
updated the first time, immediately before updated()
is called.
This method can be useful for capturing references to rendered static nodes that
must be directly acted upon, for example in updated()
.
Setting properties inside this method will trigger the element to update.
updated(changedProperties)
: (protected) Called whenever the element's DOM has been
updated and rendered. Implement to perform post updating tasks via DOM APIs, for example,
focusing an element. Setting properties inside this method will trigger the element to update.
updateComplete
: Returns a Promise that resolves when the element has completed
updating. The Promise value is a boolean that is true
if the element completed the
update without triggering another update. The Promise result is false
if a
property was set inside updated()
. This getter can be implemented to await additional state.
For example, it is sometimes useful to await a rendered element before fulfilling
this Promise. To do this, first await super.updateComplete
then any subsequent state.
requestUpdate(name?, oldValue?)
: Call to request the element to asynchronously
update regardless of whether or not any property changes are pending. This should
be called when an element should update based on some state not triggered
by setting a property. In this case, pass no arguments. It should also be called
when manually implementing a property setter. In this case, pass the property
name
and oldValue
to ensure that any configured property options are honored.
Returns the updateComplete
Promise which is resolved when the update completes.
createRenderRoot()
(protected): Implement to customize where the
element's template is rendered by returning an element into which to
render. By default this creates a shadowRoot for the element.
To render into the element's childNodes, return this
.
element.foo = 5
).hasChanged(value, oldValue)
returns false
, the element does not
update. If it returns true
, requestUpdate()
is called to schedule an update.requestUpdate()
: Updates the element after awaiting a microtask (at the end
of the event loop, before the next paint).performUpdate()
: Performs the update, calling the rest of the update API.shouldUpdate(changedProperties)
: The update proceeds if this returns true
, which
it does by default.update(changedProperties)
: Updates the element. Setting properties inside this
method will not trigger another update.
render()
: Returns a lit-html
TemplateResult (e.g. html`Hello ${world}`
)
to render element DOM. Setting properties inside this method will not trigger
the element to update.firstUpdated(changedProperties)
: Called after the element is updated the first time,
immediately before updated
is called. Setting properties inside this method will
trigger the element to update.updated(changedProperties)
: Called whenever the element is updated.
Setting properties inside this method will trigger the element to update.updateComplete
Promise is resolved with a boolean that is true
if the
element is not pending another update, and any code awaiting the element's
updateComplete
Promise runs and observes the element in the updated state.Note, this example uses decorators to create properties. Decorators are a proposed standard currently available in TypeScript or Babel.
import {LitElement, html, property} from '@polymer/lit-element';
class MyElement extends LitElement {
// Public property API that triggers re-render (synced with attributes)
@property()
foo = 'foo';
@property({type: Number})
whales = 5;
constructor() {
super();
this.addEventListener('click', async (e) => {
this.whales++;
await this.updateComplete;
this.dispatchEvent(new CustomEvent('whales', {detail: {whales: this.whales}}))
});
}
// Render method should return a `TemplateResult` using the provided lit-html `html` tag function
render() {
return html`
<style>
:host {
display: block;
}
:host([hidden]) {
display: none;
}
</style>
<h4>Foo: ${this.foo}</h4>
<div>whales: ${'🐳'.repeat(this.whales)}</div>
<slot></slot>
`;
}
}
customElements.define('my-element', MyElement);
<my-element whales="5">hi</my-element>
The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge. In addition, Internet Explorer 11 is also supported.
id
or name
) may not have default values set in the element constructor.
On these browsers native properties appear on instances and therefore their default value
will overwrite any element default (e.g. if the element sets this.id = 'id' in the constructor,
the 'id' will become '' since this is the native platform default).[0.7.0] - 2019-01-10
static get styles()
to allow defining element styling separate from render
method.
This takes advantage of adoptedStyleSheets
when possible (#391).performUpdate
method to allow control of update timing (#290).TemplateResult
and SVGTemplateResult
(#415).createRenderRoot
method has moved from UpdatingElement
to LitElement
. Therefore, UpdatingElement
no longer creates a shadowRoot
by default (#391).converter
. This option works the same as the previous type
option except that the converter
methods now also get type
as the second argument. This effectively changes type
to be a hint for the converter
. A default converter
is used if none is provided and it now supports Boolean
, String
, Number
, Object
, and Array
(#264).converter
is used. Now, the oppose is also true. When a property changes as a result of an attribute changing, the attribute is prevented from mutating again (https://github.com/Polymer/lit-element/issues/264))FAQs
Polymer based lit-html custom element
We found that @polymer/lit-element demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 12 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.