Best way to event from a LiveView to a child LiveComponent

I have a sample LiveView defined as follows:

defmodule MyAppWeb.HelloLiveView do
  use Phoenix.LiveView

  alias MyAppWeb.DisplayComponent

  def render(assigns) do
    ~H"""
    <.live_component module={DisplayComponent} id="display" />
    <button phx-click="increment" phx-target="#h1">
        Increment Count
    </button>
    """
  end
end

The DisplayComponent LiveComponent module, is defined like this:

defmodule MyAppWeb.DisplayComponent do
  use Phoenix.LiveComponent

  def mount(socket) do
    socket = assign(socket, count: 0)
    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <h1 id="h1">The count is: <%= @count %></h1>
    """
  end

  def handle_event("increment", _params, socket) do
    count = socket.assigns.count
    {:noreply, assign(socket, count: count + 1)}
  end
end

With this code, when the button is pressed in the LiveView, my handle_event callback in DisplayComponent is invoked as was my intention.

However, I was surprised that I wasn’t able to use my LiveComponent id of “display” as the button event phx-target.

Is there not a way to use the LiveComponent id to formulate the phx-target value?

If not, is there a better way to do it then the way I coded it?

You’re passing in the id in the live_component call, but you’re not using it in the component template.
This should work. (don’t forget to change phx-target)

<h1 id={@id}>The count is: <%= @count %></h1>
1 Like

Yeah, that’s a pretty good way to do it. I am surprised though that there isn’t a supported way to do this by passing the LiveComponent ID to the phx-target attribute. Thanks

Maybe you could consider marking @Internets post as the solution to your problem. This would help other readers.