Aurelia template form with Object Array


#1

How do I create aurelia forms with an binded object array?
I have a main object that includes an array of sub-objects. Now I want to create one html form providing fields for the main object and all sub-objects, so that the user can add objects to the array dynamically.

<form>
 <input type="text" name="header-title" value.bind="object.header" />
<input type="text" name="sub-object1-title" value.bind="object.subObjects.title" />
<input type="text" name="sub-object2-title" value.bind="object.subObjects.title" />
... dynamically ...

</form>

Can someone give me a hint, how to code that?


#2

Is this what you mean?

app.js

export class App {
  items = [];
  
  constructor(){
    this.items.push(new Item("item1","This is item 1"));
    this.items.push(new Item("item2","This is item 2"));
    this.items.push(new Item("item3","This is item 3"));
  }
}

class Item{
  constructor(name, value){
    this.name = name;
    this.value = value;
  }
}

app.html

<template>
  <div repeat.for="item of items">
    <input type="text" name="item.name" value.bind="item.value" />
  </div>
</template>

Then you can just push a new item on to the array when needed.


#3

Many thanks. Now I have one additional question. Is there any trick in aurelia to add new “dynamic” DOM elements to the Aurelia-Binding-Template?

Currently new elements are not considered by aurelia (e.g. using the Bootstrap collapsable).


#4

Not completely sure what you mean, but this works to show/hide using bootstrap collapse.

<template>
  <div repeat.for="item of items">
    <a href="#" data-target="${'#' + item.name}" data-toggle="collapse">Toggle ${item.name}</a>
    <input class="collapse" type="text" id="${item.name}" name="item.name" value.bind="item.value" />
  </div>
</template>

#5

Thank you for the response. Yes, this example works. I found my mistake… adding new elements to the array (e.g. with a button with click.delegate=“addNewItem()”) I forgot to give the new item a key so that the collapse had no unique identifier.

Many thanks for taking the time to give support. :slight_smile: