I have this scenario all the time: a list of entities (say Customer) and a form to edit the selected entity. I bind the form fields to properties of the currently selected entity like this:
<some-element value="${this.selectedCustomer.name}"></some-element>
This works as long as I have a selectedCustomer
which is not always the case. When I don't have one, the form is supposed to be blank. I figured that the ternary operator could be used like this:
<some-element value="${this.selectedCustomer ? this.selectedCustomer.name : ''}"></some-element>
But then the problem goes on with the name
property which might be null (looks artifical with Customer entities but is very important for me with nullable properties!). I can fix that with the ternary operator again:
<some-element value="${this.selectedCustomer ? (this.selectedCustomer.name ? this.selectedCustomer.name : '') : ''}"></some-element>
And this had to be done for all form fields for all entities. I just want ask for any experience whether this is the best way to do it?
Because lit-html expressions are just JavaScript, you have to do error handling as you would do in any other plain JavaScript. In this case you need to guard against undefined
and there's nothing lit-html can do about that because it never sees the expression, just the resulting value.
As pointed out in the comments, JavaScript itself has addressed this now with the optional chaining and nullish coalescing operators:
You last example can now look like this:
html`<some-element value=${this.selectedCustomer?.name ?? ''}></some-element>`
This is supported in Chrome, Firefox, Edge, Babel, TypeScript and should be coming soon to Safari.