Optional targets

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…

1 Like

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)
    }
  }
}
5 Likes

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

1 Like

I think that it would be nicer and more intuitive if we could simply check if specific target is null.