How do I disable a button conditionally in HEEX?

I want to disable an HTML button conditionally in a HEEX template. Currently I am doing this:

<%= if @valid_sheet do %>
    <button phx-click="save" name="save" value={@sheet_id}> 
        Save
    </button>
<% else %>
    <button phx-click="save" name="save" value={@sheet_id} disabled> 
        Save
    </button>
<% end %>

But I would rather just write a button into my html code only once and merely add the disabled attribute conditionally, as follows:

<button phx-click="save" name="save" value={@sheet_id} {if not @valid_sheet, do: "disabled"}> 
        Save
</button>

But it gives me this error: “Enumerable not implemented for “disabled” of type BitString”

How can I conditionally add an attribute to an html element?

I found the answer here: Interpolating boolean attributes in HEEx - #4 by jaimeiniesta

Apologies for not searching more assiduously before asking a question in the forums.

Here is what my HEEX looks like now:

<button phx-click="save" name="save" value={@sheet_id} disabled={not @valid_sheet}> 
        Save
</button>

This will result in the disabled attribute disappearing entirely (rather than being set as disabled="false"), which is what I wanted.

8 Likes