ref
The ref
directive allows you to grab a reference of a DOM element. Its value must be the name of the property you want
to assign the reference to.
You can access all the dom element references with the $refs
property in the class;
class InputField extends WebComponent {
static observedAttributes = ['label', 'value', 'name', 'type', 'error-message'];
onMount() {
// the $refs object will contain all the DOM references
const {fieldInput} = this.$refs;
fieldInput.focus();
}
get template() {
return `
<label class="input-field">
<input ref="fieldInput" type="{type}" name="{name}" value="{value}">
</label>
`
}
}
InputField.register();
Think of ref
as the querySelector
and querySelectorAll
, only that you
set it directly on the tag you want to grab the elements of.
ref and repeat
The ref
directive can be used with repeat
as well. This means that instead of a single DOM element, you will have
an array of DOM elements.
class FlatList extends WebComponent {
items = {
'first': 200,
'second': 800,
'third': 400,
};
onMount() {
// the $refs object will contain all the DOM references
const {items} = this.$refs;
items.forEach(item => {
console.log('item', item);
});
}
get template() {
return `
<div ref="items" repeat="items">{key} item: {$item}</div>
`
}
}
What this means is that if you use the same name for the ref
directive in multiple elements, you will get an array of
DOM elements instead of a single DOM element.
Deep References
The way CWCO handles components allows you to grab deep renferences of elements.
class CompOne extends WebComponent {
get template() {
return '<div ref="deepBox">box</div>'
}
}
CompOne.register();
class CompTwo extends WebComponent {
onMount() {
// grap a descendant element ref
const {box} = this.$refs;
// now you can use the element
// to reach into its references
const {deepBox} = box.$refs || {};
}
get template() {
return '<comp-one ref="box"></comp-one>'
}
}
CompTwo.register();
One thing to be careful about here is if CompOne
is not registered before you try to access
its references. The $refs
only exists for CWCO components and is an element is not registered as so,
it is simply a HTMLElement
instance.