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
    <.live_component module={DisplayComponent} id="display" />
    <button phx-click="increment" phx-target="#h1">
        Increment Count

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}

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

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

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.