Search code examples
web-componentlit-elementlit

LitElement object property is null


I have a component which takes an object as a property, but for some reason when rendering this.item is undefined.

@property({type: Object}) item?: {
    family: {iconUrl: string; name: string};
} | null;

static get styles(): CSSResult[] {
    return [
        css`
            ${unsafeCSS(styles)}
        `
    ];
}

render(): TemplateResult {
    if (this.item) { 
       return html`<div>found item</div>
     } else {
       return html`<div>item not found</div>
     }
}
 

In my HTML I have the following:

const item = {  
   family: {
      name: 'title',
      iconUrl: 'url'
   } 

}

html`<my-component item="${item}"></my-component>

Is there something I'm missing in order to accept an object as an argument? I've tried adjusting a number of things such as making the arg .item="{ }" with no avail.


Solution

  • Use the property syntax without string quotes:

    html`<my-component .item=${item}></my-component>`
    

    You can tell Lit to not check for the string attribute:

    @property({attribute: false}) item?: {
        family: {iconUrl: string; name: string};
    };
    

    You don't need an explicit null unless you want to handle it differently from undefined (which is the default if you don't set it).