← til

Using Ember's element ID helper

December 8, 2016

Had multiple input file fields and I've set them to

{{file-field value=imageUrl name="file" id="file" class="inputfile"}}
<label for="file" class="btn btn-default inputfile-btn">

Notice how the label's for attribute has to match file-field's id attribute. This is placed into a component that gets rendered multiple times, so we'll arrive at a problem of having multiple elements with the multiple identical ids on the page.

We could use a naive approach and then add a property for id attribute with random number like so:

import Ember from 'ember';

export default Ember.Component.extend({
  elementId: Ember.computed(function(){
    return Math.round(Math.random() * 1000);

And use it in the template like so

{{file-field value=imageUrl name="file" id=elementId class="inputfile"}}
<label for={{elementId}} class="btn btn-default inputfile-btn">

This approach is naive and doesn't guarantee that no two items with the same element id will appear. A better solution is to simply use Ember's built in concat helper with elementId.

{{file-field value=imageUrl name="file" id=(concat elementId '-file')}}
<label for={{concat elementId '-file'}} class="btn">

With this, we pass Ember's generated elementId and use it in label's for attribute.

Did you like this article? You can follow me on Twitter or subscribe to the RSS feed if you'd like to follow along.