typescriptvitelit

Lit element object property value and placeholder is undefined


How can I solve it, without changing the value of the property, since I don't want to initialize it with an empty string

@customElement('mediator-element')
export class MediatorElement extends XmBaseElement {

  @property({ type: String }) value: string;
  @property({ type: String }) id!: string;
  @property({ type: String }) placeholder: string;
  
  protected render(): TemplateResult {
    return InputTemplate.bind(this)(this);
  }
}

export const InputTemplate = (attr: Input): TemplateResult => html
  <input
    id='${attr._uuid}'
    .?value='${attr.value}'
    .?placeholder='${attr.placeholder}'
  />

If I leave it, it handles with .? It doesn't show me anything in the placeholder. Empty sample

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <script type="module" src="mediator-element.js"></script>
  <title>Lit code sample</title>
</head>
<body>
  <mediator-element
      placeholder="Ingrese su correo"
    ></mediator-element>
</body>
</html>

But if I do it alone . It shows me an undefined in the placeholder

export const InputTemplate = (attr: Input): TemplateResult => html
  <input
    id='${attr._uuid}'
    .value='${attr.value}'
    .placeholder='${attr.placeholder}'
  />

Solution

  • You can use ifDefined directive to sets the attribute if the value is defined and removes the attribute if the value is undefined.

    export const InputTemplate = (attr: Input): TemplateResult => html`
      <input
        id='${ifDefined(attr._uuid)}'
        .value='${ifDefined(attr.value)}'
        .placeholder='${ifDefined(attr.placeholder)}'
      />
      `
    

    OR

    Use nothing over other falsy values as it provides a consistent behavior between various expression binding contexts

    export const InputTemplate = (attr: any): TemplateResult => html`
      <input
        id=`${attr._uuid || nothing}`
        .value=`${attr.value || nothing}`
        .placeholder=`${attr.placeholder || nothing}`
      />
      `
    

    Reference

    Example