packages/lit-dev-content/site/tutorials/content/tooltip/08.md
The tooltip supports good performance via lazy creation, but using the
lazy API is cumbersome. In addition, the tooltip content
doesn't update when the greeted person's name changes.
A Lit directive can address these issues by encapsulating the tooltip's lazy
API. Users of the directive will use an
element expression
on the target element and provide a
TemplateResult
containing the tooltip content.
A scaffold for the directive is set up for you with the update method already
completed. It stores the directive part and the tooltipContent passed in so
you can use them in the methods you'll add: setupLazy and
renderTooltipContent.
Implement the setupLazy method. It should set didSetupLazy
so that it's only called once and then call SimpleTooltip.lazy. The call to
lazy will store the tooltip on the directive and then call the
renderTooltipContent method that you'll implement next.
{% switchable-sample %}
setupLazy() {
this.didSetupLazy = true;
SimpleTooltip.lazy(this.part!.element, (tooltip: SimpleTooltip) => {
this.tooltip = tooltip;
this.renderTooltipContent();
});
}
setupLazy() {
this.didSetupLazy = true;
SimpleTooltip.lazy(this.part.element, (tooltip) => {
this.tooltip = tooltip;
this.renderTooltipContent();
});
}
{% endswitchable-sample %}
Next implement the renderTooltipContent method. It will call Lit's
render function to render the tooltipContent into the tooltip element.
You'll use the part's renderOptions so they stay in sync. Also, make sure
to import render from Lit.
{% switchable-sample %}
import {html, css, LitElement, render} from 'lit';
//...
renderTooltipContent() {
render(this.tooltipContent, this.tooltip!, this.part!.options);
}
import {html, css, LitElement, render} from 'lit';
//...
renderTooltipContent() {
render(this.tooltipContent, this.tooltip, this.part.options);
}
{% endswitchable-sample %}
Now open the <code>my-content.<ts-js></ts-js></code> module. That cumbersome
code you previously added to call lazy in firstUpdated has been removed.
Import the tooltip directive, find the greeting, and add the directive there.
import {tooltip} from './simple-tooltip.js';
<p>
<span ${tooltip(html`${this.name}, there's coffee available in the lounge.`)}>
Hello, ${this.name}!
</span>
</p>
{% aside "info" "no-header" %}
The TooltipDirective is just rendering text here, but since the directive
takes any value Lit can render, it could include rich HTML elements like images
or tables.
{% endaside %}
Finally, interact with the greeting to verify that the tooltip works.