0

I want to dynamically add an attribute to a Lit anchor element but I can't figure out how to do it. Specifically I want to add the download attribute.

Simple Attribute

This works:

return html`<a ?disabled=${this.disabled} download>Click here</a>`

This does not:

const downloadAttribute = this.download ? "download" : "";
return html`<a ?disabled=${this.disabled} ${downloadAttribute}>Click here</a>`

Attribute With Value

This works:

return html`<a ?disabled=${this.disabled} download=${fileName}>Click here</a>`

This does not:

const downloadAttribute = this.download ? `download=${filename}` : "";
return html`<a ?disabled=${this.disabled} ${downloadAttribute}>Click here</a>`

Any ideas as to how to get Lit to read downloadAttribute as an attribute and not as a string that it ignores?

YoungDinosaur
  • 1,550
  • 17
  • 22
  • Did you try `?download=${this.download}`, assuming `this.download` is Boolean? I have no experience with Lit, just basing it on the pattern of `disabled`... – Heretic Monkey Dec 29 '22 at 21:35
  • Yes you are correct that does work. I have added a second scenario where the filename may or may not be included. – YoungDinosaur Dec 29 '22 at 22:02

2 Answers2

1

I believe it should be like:

import { ifDefined } from 'lit/directives/if-defined.js';
return html`<a ?disabled=${this.disabled} download=${ifDefined(fileName)}>Click here</a>`

As per documentation: https://lit.dev/docs/api/directives/#ifDefined

0

For boolean attributes, you can add a ? in front of the attribute within the template.

return html`
  <a ?disabled=${this.disabled} ?download=${this.download}>
    Click here
  </a>`;

For conditionally adding an attribute, use the ifDefined directive.

import {ifDefined} from 'lit/directives/if-defined.js';


return html`
  <a
    ?disabled=${this.disabled}
    download=${ifDefined(this.download ? filename : undefined)}
  >Click here</a>`;
Augustine Kim
  • 841
  • 1
  • 5