W3cubDocs

/Lit 3

Directives

directive asyncAppendSource

A directive that renders the items of an async iterable[1], appending new values after previous values, similar to the built-in support for iterables. This directive is usable only in child expressions.

Import

import { asyncAppend } from 'lit/directives/async-append.js';

Signature

asyncAppend(value, _mapper?): DirectiveResult<AsyncAppendDirective>

Parameters

value
AsyncIterable<unknown>

An async iterable

_mapper?
(v: unknown, index?: number) => unknown

Details

Async iterables are objects with a [Symbol.asyncIterator] method, which returns an iterator who's next() method returns a Promise. When a new value is available, the Promise resolves and the value is appended to the Part controlled by the directive. If another value other than this directive has been set on the Part, the iterable will no longer be listened to and new values won't be written to the Part. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

class AsyncAppendDirectiveSource

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

Import

import { AsyncAppendDirective } from 'lit/directives/async-append.js';

Details

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

Methods and properties

new AsyncAppendDirective(partInfo): AsyncAppendDirective

Parameters
partInfo
PartInfo

isConnected: booleanSource

The connection state for this Directive.

commitValue(value, index): voidSource

Parameters
value
unknown
index
number

disconnected(): voidSource

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

reconnected(): voidSource

render(value, _mapper?): symbolSource

Parameters
value
AsyncIterable<T>
_mapper?
Mapper<T>

setValue(value): voidSource

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

Parameters
value
unknown

The value to set

Details

This method should not be called synchronously from a directive's update or render.

update(part, params): undefined | noChangeSource

Parameters
part
ChildPart
params
[value, _mapper]

directive asyncReplaceSource

A directive that renders the items of an async iterable[1], replacing previous values with new values, so that only one value is ever rendered at a time. This directive may be used in any expression type.

Import

import { asyncReplace } from 'lit/directives/async-replace.js';

Signature

asyncReplace(value, _mapper?): DirectiveResult<AsyncReplaceDirective>

Parameters

value
AsyncIterable<unknown>

An async iterable

_mapper?
Mapper<unknown>

Details

Async iterables are objects with a [Symbol.asyncIterator] method, which returns an iterator who's next() method returns a Promise. When a new value is available, the Promise resolves and the value is rendered to the Part controlled by the directive. If another value other than this directive has been set on the Part, the iterable will no longer be listened to and new values won't be written to the Part. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

class AsyncReplaceDirectiveSource

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

Import

import { AsyncReplaceDirective } from 'lit/directives/async-replace.js';

Details

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

Methods and properties

new AsyncReplaceDirective(_partInfo): AsyncReplaceDirective

Parameters
_partInfo
PartInfo

isConnected: booleanSource

The connection state for this Directive.

commitValue(value, _index): voidSource

Parameters
value
unknown
_index
number

disconnected(): voidSource

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

reconnected(): voidSource

render(value, _mapper?): symbolSource

Parameters
value
AsyncIterable<T>
_mapper?
Mapper<T>

setValue(value): voidSource

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

Parameters
value
unknown

The value to set

Details

This method should not be called synchronously from a directive's update or render.

update(_part, __namedParameters): undefined | noChangeSource

Parameters
_part
ChildPart
__namedParameters
[value, _mapper]

directive cacheSource

Enables fast switching between multiple templates by caching the DOM nodes and TemplateInstances produced by the templates.

Import

import { cache } from 'lit/directives/cache.js';

Signature

cache(v): DirectiveResult<CacheDirective>

Parameters

v
unknown

Details

Example:

let checked = false;
html`
  ${cache(checked ? html`input is checked` : html`input is not checked`)}
`

class CacheDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { CacheDirective } from 'lit/directives/cache.js';

Methods and properties

new CacheDirective(partInfo): CacheDirective

Parameters
partInfo
PartInfo

render(v): Array<unknown>Source

Parameters
v
unknown

update(containerPart, __namedParameters): Array<unknown>Source

Parameters
containerPart
ChildPart
__namedParameters
[v]

directive chooseSource

Chooses and evaluates a template function from a list based on matching the given value to a case.

Import

import { choose } from 'lit/directives/choose.js';

Signature

choose(value, cases, defaultCase?): undefined | V

Parameters

value
T
cases
Array<[T, () => V]>
defaultCase?
() => V

Details

Cases are structured as [caseValue, func]. value is matched to caseValue by strict equality. The first match is selected. Case values can be of any type including primitives, objects, and symbols. This is similar to a switch statement, but as an expression and without fallthrough.

directive classMapSource

A directive that applies dynamic CSS classes.

Import

import { classMap } from 'lit/directives/class-map.js';

Signature

classMap(classInfo): DirectiveResult<ClassMapDirective>

Parameters

classInfo
ClassInfo

Details

This must be used in the class attribute and must be the only part used in the attribute. It takes each property in the classInfo argument and adds the property name to the element's classList if the property value is truthy; if the property value is falsey, the property name is removed from the element's class. For example {foo: bar} applies the class foo if the value of bar is truthy.

class ClassMapDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { ClassMapDirective } from 'lit/directives/class-map.js';

Methods and properties

new ClassMapDirective(partInfo): ClassMapDirective

Parameters
partInfo
PartInfo

render(classInfo): stringSource

Parameters
classInfo
ClassInfo

update(part, __namedParameters): string | noChangeSource

Parameters
part
AttributePart
__namedParameters
[classInfo]

type ClassInfoSource

A key-value set of class names to truthy values.

Import

import { ClassInfo } from 'lit/directives/class-map.js';

directive guardSource

Prevents re-render of a template function until a single value or an array of values changes.

Import

import { guard } from 'lit/directives/guard.js';

Signature

guard(_value, f): DirectiveResult<GuardDirective>

Parameters

_value
unknown
f
() => unknown

the template function

Details

Values are checked against previous values with strict equality (===), and so the check won't detect nested property changes inside objects or arrays. Arrays values have each item checked against the previous value at the same index with strict equality. Nested arrays are also checked only by strict equality. Example:

html`
  <div>
    ${guard([user.id, company.id], () => html`...`)}
  </div>
`

In this case, the template only rerenders if either user.id or company.id changes. guard() is useful with immutable data patterns, by preventing expensive work until data updates. Example:

html`
  <div>
    ${guard([immutableItems], () => immutableItems.map(i => html`${i}`))}
  </div>
`

In this case, items are mapped over only when the array reference changes.

class GuardDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { GuardDirective } from 'lit/directives/guard.js';

Methods and properties

new GuardDirective(_partInfo): GuardDirective

Parameters
_partInfo
PartInfo

render(_value, f): unknownSource

Parameters
_value
unknown
f
() => unknown

update(_part, __namedParameters): unknownSource

Parameters
_part
Part
__namedParameters
[_value, f]

directive ifDefinedSource

For AttributeParts, sets the attribute if the value is defined and removes the attribute if the value is undefined.

Import

import { ifDefined } from 'lit/directives/if-defined.js';

Signature

ifDefined(value): nothing | NonNullable<T>

Parameters

value
T

Details

For other part types, this directive is a no-op.

directive joinSource

Returns an iterable containing the values in items interleaved with the joiner value.

Import

import { join } from 'lit/directives/join.js';

Signature

join(items, joiner): Iterable<I | J>

Parameters

items
undefined | Iterable<I>
joiner
(index: number) => J

directive keyedSource

Associates a renderable value with a unique key. When the key changes, the previous DOM is removed and disposed before rendering the next value, even if the value - such as a template - is the same.

Import

import { keyed } from 'lit/directives/keyed.js';

Signature

keyed(k, v): DirectiveResult<Keyed>

Parameters

k
unknown
v
unknown

Details

This is useful for forcing re-renders of stateful components, or working with code that expects new data to generate new HTML elements, such as some animation techniques.

class KeyedSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { Keyed } from 'lit/directives/keyed.js';

Methods and properties

new Keyed(_partInfo): Keyed

Parameters
_partInfo
PartInfo

key: unknownSource

render(k, v): unknownSource

Parameters
k
unknown
v
unknown

update(part, __namedParameters): unknownSource

Parameters
part
ChildPart
__namedParameters
[k, v]

directive liveSource

Checks binding values against live DOM values, instead of previously bound values, when determining whether to update the value.

Import

import { live } from 'lit/directives/live.js';

Signature

live(value): DirectiveResult<LiveDirective>

Parameters

value
unknown

Details

This is useful for cases where the DOM value may change from outside of lit-html, such as with a binding to an <input> element's value property, a content editable elements text, or to a custom element that changes it's own properties or attributes. In these cases if the DOM value changes, but the value set through lit-html bindings hasn't, lit-html won't know to update the DOM value and will leave it alone. If this is not what you want--if you want to overwrite the DOM value with the bound value no matter what--use the live() directive:

html`<input .value=${live(x)}>`

live() performs a strict equality check against the live DOM value, and if the new value is equal to the live value, does nothing. This means that live() should not be used when the binding will cause a type conversion. If you use live() with an attribute binding, make sure that only strings are passed in, or the binding will update every render.

class LiveDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { LiveDirective } from 'lit/directives/live.js';

Methods and properties

new LiveDirective(partInfo): LiveDirective

Parameters
partInfo
PartInfo

render(value): unknownSource

Parameters
value
unknown

update(part, __namedParameters): unknownSource

Parameters
part
AttributePart
__namedParameters
[value]

directive mapSource

Returns an iterable containing the result of calling f(value) on each value in items.

Import

import { map } from 'lit/directives/map.js';

Signature

map(items, f): Generator<unknown, void, unknown>

Parameters

items
undefined | Iterable<T>
f
(value: T, index: number) => unknown

directive rangeSource

Returns an iterable of integers from start to end (exclusive) incrementing by step.

Import

import { range } from 'lit/directives/range.js';

Signature

range(end): Iterable<number>

Parameters

end
number

Details

If start is omitted, the range starts at 0. step defaults to 1.

directive createRefSource

Creates a new Ref object, which is container for a reference to an element.

Import

import { createRef } from 'lit/directives/ref.js';

Signature

createRef(): Ref<T>

directive refSource

Sets the value of a Ref object or calls a ref callback with the element it's bound to.

Import

import { ref } from 'lit/directives/ref.js';

Signature

ref(_ref): DirectiveResult<RefDirective>

Parameters

_ref
RefOrCallback

Details

A Ref object acts as a container for a reference to an element. A ref callback is a function that takes an element as its only argument. The ref directive sets the value of the Ref object or calls the ref callback during rendering, if the referenced element changed. Note: If a ref callback is rendered to a different element position or is removed in a subsequent render, it will first be called with undefined, followed by another call with the new element it was rendered to (if any).

// Using Ref object
const inputRef = createRef();
render(html`<input ${ref(inputRef)}>`, container);
inputRef.value.focus();
// Using callback
const callback = (inputElement) => inputElement.focus();
render(html`<input ${ref(callback)}>`, container);

class RefSource

An object that holds a ref value.

Import

import { Ref } from 'lit/directives/ref.js';

Methods and properties

new Ref(): Ref<T>

readonly value?: TSource

The current Element value of the ref, or else undefined if the ref is no longer rendered.

class RefDirectiveSource

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

Import

import { RefDirective } from 'lit/directives/ref.js';

Details

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

Methods and properties

new RefDirective(_partInfo): RefDirective

Parameters
_partInfo
PartInfo

isConnected: booleanSource

The connection state for this Directive.

disconnected(): voidSource

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

reconnected(): voidSource

render(_ref): symbolSource

Parameters
_ref
RefOrCallback

setValue(value): voidSource

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

Parameters
value
unknown

The value to set

Details

This method should not be called synchronously from a directive's update or render.

update(part, __namedParameters): symbolSource

Parameters
part
ElementPart
__namedParameters
[_ref]

type RefOrCallbackSource

Import

import { RefOrCallback } from 'lit/directives/ref.js';

Type

Ref | (el: Element | undefined) => void

directive repeatSource

A directive that repeats a series of values (usually TemplateResults) generated from an iterable, and updates those items efficiently when the iterable changes based on user-provided keys associated with each item.

Import

import { repeat } from 'lit/directives/repeat.js';

Signature

repeat(items, keyFnOrTemplate, template?): unknown

Parameters

items
Iterable<T>
keyFnOrTemplate
KeyFn<T> | ItemTemplate<T>
template?
ItemTemplate<T>

Details

Note that if a keyFn is provided, strict key-to-DOM mapping is maintained, meaning previous DOM for a given key is moved into the new position if needed, and DOM will never be reused with values for different keys (new DOM will always be created for new keys). This is generally the most efficient way to use repeat since it performs minimum unnecessary work for insertions and removals. The keyFn takes two parameters, the item and its index, and returns a unique key value.

html`
  <ol>
    ${repeat(this.items, (item) => item.id, (item, index) => {
      return html`<li>${index}: ${item.name}</li>`;
    })}
  </ol>
`

Important: If providing a keyFn, keys must be unique for all items in a given call to repeat. The behavior when two or more items have the same key is undefined. If no keyFn is provided, this directive will perform similar to mapping items to values, and DOM will be reused against potentially different items.

class RepeatDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { RepeatDirective } from 'lit/directives/repeat.js';

Methods and properties

new RepeatDirective(partInfo): RepeatDirective

Parameters
partInfo
PartInfo

render(items, template): Array<unknown>Source

Parameters
items
Iterable<T>
template
ItemTemplate<T>

update(containerPart, __namedParameters): Array<unknown> | noChangeSource

Parameters
containerPart
ChildPart
__namedParameters
[Iterable<T>, KeyFn<T> | ItemTemplate<T>, ItemTemplate<T>]

type ItemTemplateSource

Import

import { ItemTemplate } from 'lit/directives/repeat.js';

Type

(item: T, index: number) => unknown

type KeyFnSource

Import

import { KeyFn } from 'lit/directives/repeat.js';

Type

(item: T, index: number) => unknown

type RepeatDirectiveFnSource

Import

import { RepeatDirectiveFn } from 'lit/directives/repeat.js';

Signature

RepeatDirectiveFn(items, keyFnOrTemplate, template?): unknown

Parameters

items
Iterable<T>
keyFnOrTemplate
KeyFn<T> | ItemTemplate<T>
template?
ItemTemplate<T>

directive styleMapSource

A directive that applies CSS properties to an element.

Import

import { styleMap } from 'lit/directives/style-map.js';

Signature

styleMap(styleInfo): DirectiveResult<StyleMapDirective>

Parameters

styleInfo
Readonly<StyleInfo>

Details

styleMap can only be used in the style attribute and must be the only expression in the attribute. It takes the property names in the styleInfo object and adds the properties to the inline style of the element. Property names with dashes (-) are assumed to be valid CSS property names and set on the element's style object using setProperty(). Names without dashes are assumed to be camelCased JavaScript property names and set on the element's style object using property assignment, allowing the style object to translate JavaScript-style names to CSS property names. For example styleMap({backgroundColor: 'red', 'border-top': '5px', '--size': '0'}) sets the background-color, border-top and --size properties.

class StyleMapDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { StyleMapDirective } from 'lit/directives/style-map.js';

Methods and properties

new StyleMapDirective(partInfo): StyleMapDirective

Parameters
partInfo
PartInfo

render(styleInfo): stringSource

Parameters
styleInfo
Readonly<StyleInfo>

update(part, __namedParameters): string | noChangeSource

Parameters
part
AttributePart
__namedParameters
[styleInfo]

type StyleInfoSource

A key-value set of CSS properties and values.

Import

import { StyleInfo } from 'lit/directives/style-map.js';

Details

The key should be either a valid CSS property name string, like 'background-color', or a valid JavaScript camel case property name for CSSStyleDeclaration like backgroundColor.

directive templateContentSource

Renders the content of a template element as HTML.

Import

import { templateContent } from 'lit/directives/template-content.js';

Signature

templateContent(template): DirectiveResult<TemplateContentDirective>

Parameters

template
HTMLTemplateElement

Details

Note, the template should be developer controlled and not user controlled. Rendering a user-controlled template with this directive could lead to cross-site-scripting vulnerabilities.

class TemplateContentDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { TemplateContentDirective } from 'lit/directives/template-content.js';

Methods and properties

new TemplateContentDirective(partInfo): TemplateContentDirective

Parameters
partInfo
PartInfo

render(template): DocumentFragment | noChangeSource

Parameters
template
HTMLTemplateElement

update(_part, props): unknownSource

Parameters
_part
Part
props
Array<unknown>

directive unsafeHTMLSource

Renders the result as HTML, rather than text.

Import

import { unsafeHTML } from 'lit/directives/unsafe-html.js';

Signature

unsafeHTML(value): DirectiveResult<UnsafeHTMLDirective>

Parameters

value
undefined | null | string | noChange | nothing

Details

The values undefined, null, and nothing, will all result in no content (empty string) being rendered. Note, this is unsafe to use with any user-provided input that hasn't been sanitized or escaped, as it may lead to cross-site-scripting vulnerabilities.

class UnsafeHTMLDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { UnsafeHTMLDirective } from 'lit/directives/unsafe-html.js';

Methods and properties

new UnsafeHTMLDirective(partInfo): UnsafeHTMLDirective

Parameters
partInfo
PartInfo

static directiveName: stringSource

static resultType: numberSource

render(value): undefined | null | noChange | nothing | TemplateResult<ResultType>Source

Parameters
value
undefined | null | string | noChange | nothing

update(_part, props): unknownSource

Parameters
_part
Part
props
Array<unknown>

directive unsafeSVGSource

Renders the result as SVG, rather than text.

Import

import { unsafeSVG } from 'lit/directives/unsafe-svg.js';

Signature

unsafeSVG(value): DirectiveResult<UnsafeSVGDirective>

Parameters

value
undefined | null | string | noChange | nothing

Details

The values undefined, null, and nothing, will all result in no content (empty string) being rendered. Note, this is unsafe to use with any user-provided input that hasn't been sanitized or escaped, as it may lead to cross-site-scripting vulnerabilities.

class UnsafeSVGDirectiveSource

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

Import

import { UnsafeSVGDirective } from 'lit/directives/unsafe-svg.js';

Methods and properties

new UnsafeSVGDirective(partInfo): UnsafeSVGDirective

Parameters
partInfo
PartInfo

static directiveName: stringSource

static resultType: numberSource

render(value): undefined | null | noChange | nothing | TemplateResult<ResultType>Source

Parameters
value
undefined | null | string | noChange | nothing

update(_part, props): unknownSource

Parameters
_part
Part
props
Array<unknown>

directive untilSource

Renders one of a series of values, including Promises, to a Part.

Import

import { until } from 'lit/directives/until.js';

Signature

until(values): DirectiveResult<UntilDirective>

Parameters

values
Array<unknown>

Details

Values are rendered in priority order, with the first argument having the highest priority and the last argument having the lowest priority. If a value is a Promise, low-priority values will be rendered until it resolves. The priority of values can be used to create placeholder content for async data. For example, a Promise with pending content can be the first, highest-priority, argument, and a non_promise loading indicator template can be used as the second, lower-priority, argument. The loading indicator will render immediately, and the primary content will render when the Promise resolves. Example:

const content = fetch('./content.txt').then(r => r.text());
html`${until(content, html`<span>Loading...</span>`)}`

class UntilDirectiveSource

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

Import

import { UntilDirective } from 'lit/directives/until.js';

Details

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

Methods and properties

new UntilDirective(_partInfo): UntilDirective

Parameters
_partInfo
PartInfo

isConnected: booleanSource

The connection state for this Directive.

disconnected(): voidSource

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

reconnected(): voidSource

render(args): unknownSource

Parameters
args
Array<unknown>

setValue(value): voidSource

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

Parameters
value
unknown

The value to set

Details

This method should not be called synchronously from a directive's update or render.

update(_part, args): unknownSource

Parameters
_part
Part
args
Array<unknown>

directive whenSource

When condition is true, returns the result of calling trueCase(), else returns the result of calling falseCase() if falseCase is defined.

Import

import { when } from 'lit/directives/when.js';

Signature

when(condition, trueCase, falseCase?): T

Parameters

condition
true
trueCase
() => T
falseCase?
() => F

Details

This is a convenience wrapper around a ternary expression that makes it a little nicer to write an inline conditional without an else.

© Google LLC
Licensed under the Creative Commons Attribution 3.0 Unported License.
https://lit.dev/docs/api/directives/