Optional targets


#1

Is it possible to have optional targets? If I remove the HTML that includes the reference to the target, the whole Stimulus controller fails.

I can of course, not use a target on those particular element and get them using querySelector…


#2

You can use the has*Target properties to check for optional target elements:

export default class extends Controller {
  static targets = [ "name" ]

  connect() {
    if (this.hasNameTarget) {
      console.log(this.nameTarget)
    }
  }
}

#3

Thanks @javan, I totally skipped over that part in the docs.