Stimulus Discourse

Using a controller with an absent target?


#1

Apologies if this has been asked before, but I didn’t see it if so.

I have an input_controller that does various things to various form inputs throughout our app. However, I’m using this controller on several different pages, and as such, not all of my targets (which happen to be inputs) are going to be present on every page, so I’m seeing the “Missing target element” error in the console.

To me this would seem to imply that the controller expects all of the defined targets to be present when it connects? I hope this is not the case, as that would seem to go against the inherent “generalization” goal of stimulus controllers. Anyone have any suggestions?

Loving stimulus btw. Its been a real joy to work with so far!


#2

See:

Optional Targets

If your controller needs to work with a target which may or may not be present, condition your code based on the value of the existential target property:

if (this.hasResultsTarget) {
 this.resultsTarget.innerHTML = "…"
}

and:

Properties

For each target name defined in the static targets array, Stimulus adds the following properties to your controller, where [name] corresponds to the target’s name:

Type Name Value
Singular this.[name]Target The first matching target in scope
Plural this.[name]Targets An array of all matching targets in scope
Existential this.has[Name]Target A boolean indicating whether there is a matching target in scope

Note: Accessing the singular target property will throw an error when there is no matching element.

:beers:


#3

Awesome, appreciate you taking the time to respond. The hasXTarget was definitely the missing piece of the puzzle.
:beers: