Back to Lit

01

packages/lit-dev-content/site/tutorials/content/custom-attribute-converter/01.md

latest2.4 KB
Original Source

Lit has built-in attribute converters for basic types like number and boolean. In this step and the following one, you'll use a built-in attribute converter and some imperative code to set the date property from markup.

In this step, you start with a Lit component that:

  • Has a date reactive property of type Date.
  • Has attribute to property conversion turned off {attribute: false}.
  • Displays the date in a human-readable format.

The date property is set in index.html, using JavaScript. The date property can't be set from an attribute, because Lit doesn't have a built-in attribute converter to convert a string date to a Date object.

Attribute converters tell Lit how to convert an attribute to a property and, in the case that a reactive property has the reflect: true flag, from property to attribute.

Lit has several built-in attribute converters. You can choose which built-in converter is invoked by setting the type option when you declare a reactive property. The built-in converters are:

  • String (default)
  • Boolean
  • Number
  • Array
  • Object

For more information on built-in converters, see Using the default converter.

In this step, you'll add a new dateStr reactive property that accepts a human-readable date string, and can be set from an attribute. (That is, date-str="05/05/22".)

Add the dateStr property

  • Declare a dateStr reactive property of type String.
  • Set the default value for dateStr to a string representation of date.
  • Set the attribute for dateStr to be date-str.

date-display.<ts-js></ts-js>

{% switchable-sample %}

ts
export class DateDisplay extends LitElement {
  @property({attribute: false})
  date = new Date();

  @property({type: String, attribute: 'date-str'})
  dateStr = '';
  ...
js
export class DateDisplay extends LitElement {
  static properties = {
    date: {attribute: false},
    dateStr: {type: String, attribute: 'date-str'},
  };

  constructor() {
    super();
    this.date = new Date();
    this.dateStr = '';
  }
  ...

{% endswitchable-sample %}

Now setting the date-str attribute to 05/05/22 will update the dateStr property to 05/05/22 because the built-in String attribute converter is used! Unfortunately, you won't see any change to the output, because the date property isn't being updated.

In the next step, you'll fix that.