Directives
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
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
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
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
Permalink to constructorParameters
- partInfo
PartInfo
The connection state for this Directive.
Parameters
- value
unknown
- index
number
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.
Parameters
- value
AsyncIterable<T>
- _mapper?
Mapper<T>
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
.
Parameters
- part
ChildPart
- params
[value, _mapper]
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
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
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
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
Permalink to constructorParameters
- _partInfo
PartInfo
The connection state for this Directive.
Parameters
- value
unknown
- _index
number
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.
Parameters
- value
AsyncIterable<T>
- _mapper?
Mapper<T>
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
.
Parameters
- _part
ChildPart
- __namedParameters
[value, _mapper]
Enables fast switching between multiple templates by caching the DOM nodes and TemplateInstances produced by the templates.
Import
Signature
cache(v): DirectiveResult<CacheDirective>
Parameters
- v
unknown
Details
Example:
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new CacheDirective(partInfo): CacheDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- v
unknown
Parameters
- containerPart
ChildPart
- __namedParameters
[v]
Chooses and evaluates a template function from a list based on matching the given value
to a case.
Import
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.
A directive that applies dynamic CSS classes.
Import
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new ClassMapDirective(partInfo): ClassMapDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- classInfo
ClassInfo
Parameters
- part
AttributePart
- __namedParameters
[classInfo]
A key-value set of class names to truthy values.
Import
Prevents re-render of a template function until a single value or an array of values changes.
Import
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:
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:
In this case, items are mapped over only when the array reference changes.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new GuardDirective(_partInfo): GuardDirective
Permalink to constructorParameters
- _partInfo
PartInfo
Parameters
- _value
unknown
- f
() => unknown
Parameters
- _part
Part
- __namedParameters
[_value, f]
For AttributeParts, sets the attribute if the value is defined and removes the attribute if the value is undefined.
Import
Signature
ifDefined(value): nothing | NonNullable<T>
Parameters
- value
T
Details
For other part types, this directive is a no-op.
Returns an iterable containing the values in items
interleaved with the joiner
value.
Import
Signature
join(items, joiner): Iterable<I | J>
Parameters
- items
undefined | Iterable<I>
- joiner
(index: number) => J
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
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new Keyed(_partInfo): Keyed
Permalink to constructorParameters
- _partInfo
PartInfo
Parameters
- k
unknown
- v
unknown
Parameters
- part
ChildPart
- __namedParameters
[k, v]
Checks binding values against live DOM values, instead of previously bound values, when determining whether to update the value.
Import
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:
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new LiveDirective(partInfo): LiveDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- value
unknown
Parameters
- part
AttributePart
- __namedParameters
[value]
Returns an iterable containing the result of calling f(value)
on each value in items
.
Import
Signature
map(items, f): Generator<unknown, void, unknown>
Parameters
- items
undefined | Iterable<T>
- f
(value: T, index: number) => unknown
Returns an iterable of integers from start
to end
(exclusive) incrementing by step
.
Import
Signature
range(end): Iterable<number>
Parameters
- end
number
Details
If start
is omitted, the range starts at 0
. step
defaults to 1
.
Creates a new Ref object, which is container for a reference to an element.
Import
Signature
createRef(): Ref<T>
Sets the value of a Ref object or calls a ref callback with the element it's bound to.
Import
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).
An object that holds a ref value.
Import
Methods and properties
new Ref(): Ref<T>
Permalink to constructorThe current Element value of the ref, or else undefined
if the ref is no longer rendered.
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
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
Permalink to constructorParameters
- _partInfo
PartInfo
The connection state for this Directive.
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.
Parameters
- _ref
RefOrCallback
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
.
Parameters
- part
ElementPart
- __namedParameters
[_ref]
Import
Type
Ref | (el: Element | undefined) => void
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
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.
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new RepeatDirective(partInfo): RepeatDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- items
Iterable<T>
- template
ItemTemplate<T>
Parameters
- containerPart
ChildPart
- __namedParameters
[Iterable<T>, KeyFn<T> | ItemTemplate<T>, ItemTemplate<T>]
Import
Type
(item: T, index: number) => unknown
Import
Type
(item: T, index: number) => unknown
Import
Signature
RepeatDirectiveFn(items, keyFnOrTemplate, template?): unknown
Parameters
- items
Iterable<T>
- keyFnOrTemplate
KeyFn<T> | ItemTemplate<T>
- template?
ItemTemplate<T>
A directive that applies CSS properties to an element.
Import
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new StyleMapDirective(partInfo): StyleMapDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- styleInfo
Readonly<StyleInfo>
Parameters
- part
AttributePart
- __namedParameters
[styleInfo]
A key-value set of CSS properties and values.
Import
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
.
Renders the content of a template element as HTML.
Import
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new TemplateContentDirective(partInfo): TemplateContentDirective
Permalink to constructorParameters
- partInfo
PartInfo
Parameters
- template
HTMLTemplateElement
Parameters
- _part
Part
- props
Array<unknown>
Renders the result as HTML, rather than text.
Import
Signature
unsafeHTML(value): DirectiveResult<UnsafeHTMLDirective>
Parameters
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new UnsafeHTMLDirective(partInfo): UnsafeHTMLDirective
Permalink to constructorParameters
- partInfo
PartInfo
render(value): undefined | null | noChange | nothing | TemplateResult<2 | 1>
Permalink to render View sourceParameters
- _part
Part
- props
Array<unknown>
Renders the result as SVG, rather than text.
Import
Signature
unsafeSVG(value): DirectiveResult<UnsafeSVGDirective>
Parameters
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.
Base class for creating custom directives. Users should extend this class, implement render
and/or update
, and then pass their subclass to directive
.
Import
Methods and properties
new UnsafeSVGDirective(partInfo): UnsafeSVGDirective
Permalink to constructorParameters
- partInfo
PartInfo
render(value): undefined | null | noChange | nothing | TemplateResult<2 | 1>
Permalink to render View sourceParameters
- _part
Part
- props
Array<unknown>
Renders one of a series of values, including Promises, to a Part.
Import
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:
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
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
Permalink to constructorParameters
- _partInfo
PartInfo
The connection state for this Directive.
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.
Parameters
- args
Array<unknown>
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
.
Parameters
- _part
Part
- args
Array<unknown>
When condition
is true, returns the result of calling trueCase()
, else returns the result of calling falseCase()
if falseCase
is defined.
Import
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.