Giving components unique name using #each index


#1

So I’m building this form and I need to give form fields unique names for validation. Given the following code, I’m running into an issue:

    {{#each application.applicant as |applicant index|}}
        <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control required" name="city{{index}}" value={{applicant.job.city}}>
        </div>

            <label for="zip">Zip</label>
            {{zip-code-input class="form-control " name="zip" unmaskedValue=applicant.job.zip fullCode=false}}
    {{/each}}

For the city, adding the index to the name is no problem, but then for the zip code input, I can’t just plop the index into the name. What the cleanest way to solve this?


#2

Try using the concat helper and a subexpression:

{{zip-code-input class="form-control " name=(concat "zip" index)}}

There’s some good resources in the guides for this: https://guides.emberjs.com/v2.6.0/templates/built-in-helpers/#toc_nesting-built-in-helpers


#3

Perfect solution! Been a while since I learned something new related to ember. Thank you!