In addition to declaring dynamic parts of templates with expressions, you also have access to several powerful directives, which aid in common scenarios.
Structural directives change the shape of the DOM itself by adding and removing nodes based on the state of your element.
when directive enables you to conditionally render blocks of HTML. When you provide an expression to
when it will render the child template into the DOM when the expression evaluates to
true and remove the child template when it evaluates to
false (or if it is never
true, the rendering will be skipped entirely).
Example: Conditional Rendering
@observable decorator creates a property that the template system can watch for changes. It is similar to
@attr, but the property is not surfaced as an HTML attribute on the element itself. While
@attr can only be used in a
@observable can be used in any class.
In addition to providing a template to conditionally render, you can also provide an expression that evaluates to a template. This enables you to dynamically change what you are conditionally rendering.
Example: Conditional Rendering with Dynamic Template
To render a list of data, use the
repeat directive, providing the list to render and a template to use in rendering each item.
Example: List Rendering
Similar to event handlers, within a
repeat block you have access to a special context object. Here is a list of the properties that are available on the context:
event- The event object when inside an event handler.
parent- The parent scope when inside a
index- The index of the current item when inside a
length- The length of the array when inside a
isEven- True if the index of the current item is even when inside a
isOdd- True if the index of the current item is odd when inside a
isFirst- True if the current item is first in the array inside a
isInMiddle- True if the current item is somewhere in the middle of the array inside a
isLast- True if the current item is last in the array inside a
Some context properties are opt-in because they are more costly to update. So, for performance reasons, they are not available by default. To opt into the positioning properties, pass options to the repeat directive, with the setting
positioning: true. For example, here's how we would use the
index in our friends template from above:
Example: List Rendering with Item Index
In addition to providing a template to render the items with, you can also provide an expression that evaluates to a template. This enables you to dynamically change what you are using to render the items. Each item will still be rendered with the same template, but you can use techniques from "Composing Templates" below to render a different template depending on the item itself.
ViewTemplate returned from the
html tag helper has special handling when it is used inside of another template. This is done so that you can create templates and compose them into other templates.
Example: Composing Templates
In the above example, we create an independent
nameTemplate and then use it in two different places. First inside of a
when template and then later inside of a
But content composition is actually more powerful than that because you aren't limited to static composition of templates. You can also provide any expression that returns a template. As a result, when the
@observable dependencies of the expression change, you can dynamically change which template is selected for rendering. If you don't want to render anything, you can also handle that by returning
undefined. Here are a few examples of what you can do with content composition:
Example: Dynamic Composition
Example: Override Templates
Example: Complex Conditional
Example: Per Item List Types
Example: Custom Rendering Override
When composing templates, extract the composed template to an external variable. If you define the template inline, within your method, property, or expression, then each time that is invoked, a new instance of the template will be created, rather than reusing the template. This will result in an unnecessary performance cost.
Now that we've explained how content composition works, you may find it interesting to know that
when is actually just syntax sugar on top of the core composition system. Let's look at the implementation of
when itself to see how it works:
As you can see, all that
when does is compose a new function that checks your condition. If it's
true, it invokes your template provider function; if
false, it returns
null, indicating nothing should be rendered.
Referential directives allow you to easily get references to DOM nodes in various scenarios.
Sometimes you need a direct reference to a single DOM node from your template. This might be because you want to control the playback of a
video element, use the drawing context of a
canvas element, or pass an element to a 3rd party library. Whatever the reason, you can get a reference to the DOM node by using the
Example: Referencing an Element
ref directive on the element you want to reference and provide it with a property name to assign the reference to. Once the
connectedCallback lifecycle event runs, your property will be set to the reference, ready for use.
If you provide a type for your HTML template, TypeScript will type check the property name you provide to ensure that it actually exists on your element.
ref to reference a single DOM node, you can use
children to get references to all child nodes of a particular element.
Example: Referencing Child Nodes
In the example above, the
listItems property will be populated with all child nodes of the
ul element. If
listItems is decorated with
@observable then it will be updated dynamically as the child nodes change. Like any observable, you can optionally implement a propertyNameChanged method to be notified when the nodes change. Additionally, you can provide an
options object to the
children directive to specify a customized configuration for the underlying MutationObserver.
ref, the child nodes are not available until the
connectedCallback lifecycle event.
You can also provide a
filter function to control which child nodes are synchronized to your property. As a convenience, we provide an
elements filter that lets you optionally specify a selector. Taking the above example, if we wanted to ensure that our
listItems array only included
li elements (and not any text nodes or other potential child nodes), we could author our template like this:
Example: Filtering Child Nodes
Sometimes you may want references to all nodes that are assigned to a particular slot. To accomplish this, use the
slotted directive. (For more on slots, see Working with Shadow DOM.)
Similar to the
children directive, the
slotted directive will populate the
slottedNodes property with nodes assigned to the slot. If
slottedNodes is decorated with
@observable then it will be updated dynamically as the assigned nodes change. Like any observable, you can optionally implement a propertyNameChanged method to be notified when the nodes change. Additionally, you can provide an
options object to the
slotted directive to specify a customized configuration for the underlying assignedNodes() API call or specify a
So far, our bindings and directives have only affected elements within the Shadow DOM of the component. However, sometimes you want to affect the host element itself, based on property state. For example, a progress component might want to write various
aria attributes to the host, based on the progress state. In order to facilitate scenarios like this, you can use a
template element as the root of your template, and it will represent the host element. Any attribute or directive you place on the
template element will be applied to the host itself.
Example: Host Directive Template
Example: DOM with Host Directive Output
children directive on the
template element will provide you with references to all Light DOM child nodes of your custom element, regardless of if or where they are slotted.