Connect A Stimulus Controller To Existing HTML

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated a year ago

In this lesson, we'll take an existing HTML structure and connect it to a Stimulus controller. We'll also look at adding an "action" to a form input as well as setting an element as a "target" to connect all the dots to make a Stimulus controller functional.

Damon Bauer: [0:00] I've got some HTML that has a <div> with a list of transactions that I want to filter based on a user's input. Let's start by wiring all of this HTML up to a collection filter stimulus controller.

[0:18] On this <div> that's wrapping all of these elements, I'm adding the data-controller attribute and setting it to the name of the controller that I want to create. In this case, collection-filter.

[0:31] Now, on this input where we expect the user to type the thing they're searching for, we'll add a data-target attribute which is what we'll use in the stimulus controller to find what they typed and filter the data down by.

[0:48] The data-target attribute is provided by stimulus. It's a way to get a hook into an element in the stimulus controller to find information out about it in the DOM. In this case, we want to know what was the user value that they typed into this field.

[1:05] Next, we'll add a data-action attribute. What this data attribute says when this DOM element has an input event fired on it execute the update-filter method found on the collection-filter controller.

[1:27] Now, let's add a target to our transactions-list wrapping <div> element. What this will allow us to do is find this DOM element in our controller, so that we can find all of the transaction elements inside of it and decide whether or not we should show or hide that transaction based on the value that the user typed into the input executed by the update-filter method.