There are no tracking or monitoring cookies on this site. There are only cookies used for documentation examples related to cookies.Close
Processing...
This may take a few seconds.

Passing Variables into Components

When you are writing a re-usable component, you may want to set options for it.

You would set the options to pass in to the component as attributes on the host tag.

You would normally use a custom element for this. You can also use a regular HTML tag as a component host, but custom elements allow for more flexibility with attribute names. Custom attributes in HTML tags should be written like "data-" and then the suffix, like "data-name" or "data-reference" or whatever. That is following the standard syntax for custom attributes.

But with custom elements you can name attributes however you like. So custom elements are preferred.

You refer to these host attributes with the {@host:varname} syntax.

For example:

body:init {
create-element: hello-there hiThere;
render: "<hello-there name="Dave"></hello-there>
<hello-there name="
Shirley"></hello-there>
<hello-there name="
Tracey"></hello-there>";
}

@component hiThere {
html {
<p>Hi there {@host:name}</p>
}
}
Reactive attributes

This is also called "attribute binding". It is the binding of a variable to an attribute so that the variable changes when the attribute changes.

Custom elements allow you to have reactive attributes. Attributes can be observed on the host tag and when the attributes change, the variables that reference it inside the component can automatically update.

To do this, use the option observe, followed by the attributes to observe separated with a space.

Variables in the inner component can then be given double-curlies to turn them into reactive variables.

This method of observed attributes only works for custom element host tags.

Example:

body:init {
create-element: hello-there hiThere observe(name height);
render: "<hello-there name="Dave" height="6"></hello-there>";
hello-there {
set-attribute: name "Shirley" after 2s, height "5" after 2s;
set-attribute: name "Tracey" after 4s, height "7" after 4s;
}
}

@component hiThere {
html {
<p>Hi there {{@host:name}}. I see you are {{@host:height}} feet tall.</p>
}
}

That example renders the component once only, and then by updating the attributes of the host tag the inner contents are changed.