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?