In this episode, we dive right into some hands-on attribute binding examples, focusing mainly on dynamic lists and progress bars.
First up, we take a practical look at managing a list of people. We start by rendering a list of checkboxes, each representing a different person. As you check and uncheck them, we update the styling so that selected people stand out (like bolding their names). This demonstrates iterating through data with x-for
, binding attribute values like id
and value
, and syncing selected states with an array using x-model
. We address a common gotcha with type mismatches (numbers vs. strings in the selected array), showing solutions like using Alpine's number
modifier for consistent data.
Next, we revisit and rebuild a styled progress bar from scratch. Using dynamic style bindings, we sync a progress value to the width of the bar, and hook up a button to increment it. We also introduce the Alpine init
lifecycle hook to automatically animate the progress bar as soon as the component loads, using setInterval. As a finishing touch, we show how to stop the animation when the progress reaches its maximum.
You'll come away from this episode with a solid foundation in attribute and style binding for real-world UI elements in Alpine.js, and a sense of how to troubleshoot common pitfalls along the way.