Referencing repeated elements (SOLVED)

I am struggling with the repeater.

Is there a way to create a reference to repeated elements (in an array)? I tried something like this, but it does not seem to work:

App.html:

<template>
  <div repeat.for="i of 5" ref="divs[${i}]"></div>
</template>

App.ts:

export class App {
  divs!: Element[]; 
}

When I try to run this, I get the following error in the browser console:

Uncaught (in promise) Error: Parser Error: Missing expected token ] at column 7 in expression [divs[${i}]]
    at ParserImplementation.err (aurelia-binding.js?5f98:2857)
    at ParserImplementation.expect (aurelia-binding.js?5f98:2873)
    at ParserImplementation.parseLeftHandSide (aurelia-binding.js?5f98:2627)
    at ParserImplementation.parseBinary (aurelia-binding.js?5f98:2441)
    at ParserImplementation.parseConditional (aurelia-binding.js?5f98:2430)
    at ParserImplementation.parseExpression (aurelia-binding.js?5f98:2416)
    at ParserImplementation.parseValueConverter (aurelia-binding.js?5f98:2398)
    at ParserImplementation.parseBindingBehavior (aurelia-binding.js?5f98:2387)
    at Parser.parse (aurelia-binding.js?5f98:2349)
    at TemplatingBindingLanguage.inspectAttribute (aurelia-templating-binding.js?570d:694)

I also tried it with this markup in the view:

<div repeat.for="i of 5" ref.bind="'divs[' + i + ']'"></div>

This would not result in a browser error, but the page does not render as desired and the divs property of the viewmodel remains empty.

Is it invalid to use ref with an array to reference repeated elements? Is there perhaps another way to accomplish such thing?

1 Like

Ha! Got it to work! :slight_smile:

I was able to use the $index contextual property. I also needed to initialize the divs array to an empty array. The following code seems to work just fine:

App.html:

<template>
  <div repeat.for="i of 5" ref="divs[$index]"></div>
</template>

App.ts:

export class App {
  divs: Element[] = [];
}
2 Likes

ref values are treated as expression, not just a simple string. And ref is a special attribute, I think this is why it got you confused :sweat:

Here’s an example of it close to what you originally got: https://gist.dumber.app/?gist=32229d23a7f76b91b6347ea19a01d093

Because it’s an expression, so you gotta do either:

  <div repeat.for="i of 5" ref="divs[i]">
    ${i}
  </div>

or

  <div repeat.for="i of 5" ref="divs[`${i}`]">
    ${i}
  </div>

As divs[${i}] is an invalid expression, hence the error you saw when the parser tries to parse it into an ast.

3 Likes

Ooh! :open_mouth: :grimacing: :sweat_smile:
So it was even easier than I thought! Great!
Thanks a lot!

1 Like