How to add a child component to the main component through javascript in Ember Octane

Hi,

I have main component with a button. Whenever this button is clicked I want to instantiate and add a child component to a “div” in the main component . It’s like adding rows on button click. How do I implement this behavior.

Here is the pseudo code.

MainCompoent.hbs

<div id="placeHolder>   </div>
<button onClick={{this.clickAdd}}> Add </button>


MainCompoent.js
 @action
 clickAdd() {
   //How to initialize Row Component and add to the placeHolder
   // For example document.getElementById("placeHolder").innerHTML += `<RowComponent/>`;
}

RowComponent.hbs
  <div>    
    <input name>  
    <input age>   
 </div>

r1

You need to keep a list of rows in your MainComponent. The details depend on what exactly you want to do with the rows, but here’s an example where each one stores just a name input field:

import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';

export default class MainComponent extends Component {
  @tracked
  rows = [];

  @action
  clickAdd() {
    this.rows = [...this.rows, { @tracked name: "" }];
  }

  get summary() {
    return `There are ${this.rows.length} rows, and they contain these names: ${this.rows.map(row => row.name).join(" ")}`
  }
}
<button {{on "click" this.clickAdd}}> Add </button>

{{#each this.rows as |row|}}
  <div>
   {{! Here I am just creating an Input, but you could
       also call your RowComponent here. }}
    <Input @value={{row.name}} />
  </div>
{{/each}}

<div>
  Summary: {{this.summary}}
</div>
1 Like

Thanks Edward. This approach suits my usecase.