How to create dynamic accordion component ember.js?

Member

by dana , in category: Javascript , 3 months ago

How to create dynamic accordion component ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 3 months ago

@dana 

To create a dynamic accordion component in Ember.js, you can follow these steps:

  1. Generate a new component using the Ember CLI:
1
$ ember generate component dynamic-accordion


  1. Update the template for the dynamic accordion component (app/templates/components/dynamic-accordion.hbs) to include the accordion structure and content. You can use Bootstrap or any other CSS framework for styling the accordion:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<div class="accordion">
  {{#each items as |item index|}}
    <div class="accordion-item">
      <div class="accordion-header" {{action "toggleAccordion" index}}>
        {{item.title}}
      </div>
      {{#if item.isExpanded}}
        <div class="accordion-content">
          {{item.content}}
        </div>
      {{/if}}
    </div>
  {{/each}}
</div>


  1. Define the actions and state for the dynamic accordion component in the component's JavaScript file (app/components/dynamic-accordion.js):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import Component from '@ember/component';

export default Component.extend({
  items: null,

  actions: {
    toggleAccordion(index) {
      this.items.forEach((item, i) => {
        if (i === index) {
          item.isExpanded = !item.isExpanded;
        } else {
          item.isExpanded = false;
        }
      });
    }
  }
});


  1. Create a route or controller to load the data for the accordion items and pass it to the dynamic accordion component in the template:
1
{{dynamic-accordion items=model.accordionItems}}


  1. Update your data model or controller to include the accordion items:
1
2
3
4
5
6
7
export default Controller.extend({
  accordionItems: [
    { title: 'Accordion Item 1', content: 'Lorem ipsum dolor sit amet.', isExpanded: false },
    { title: 'Accordion Item 2', content: 'Consectetur adipiscing elit.', isExpanded: false },
    { title: 'Accordion Item 3', content: 'Sed do eiusmod tempor incididunt ut labore et dolore.', isExpanded: false }
  ]
});


  1. Style the accordion component in your application's CSS file to achieve the desired look and feel.


Now you have a dynamic accordion component in your Ember.js application that can expand and collapse accordion items based on user interaction. Feel free to customize the accordion structure and styling to suit your application's design requirements.