I have a template with titles and details. How do I create a toggle view details when you click the title

I have a template with titles and details. How do I create a toggle view for h3 to display the div with details when you click the title.

I need help or a little demo and some guidance so I can learn. I currently have an app on GitHub.

Here is my template code:

<h2>Titles</h2>
{{outlet}}

{{#each pagedContent as |post|}}
      <div class="listing">
/* Click*/
          <h3>{{post.title}}</h3>
/* Toggle view below*/
          <p>{{post.body}}</p>
          <p>User Name: {{post.userId.username}} </p>
          <p>Company: {{post.userId.company.name}}</p>
            {{!-- TODO: Fix format --}}
            <p><a href="{{post.userId.website}}"></a></p>
            <p>Catchphrase: {{post.userId.company.catchPhrase}}</p>

            <p>Author's Name: {{post.userId.name}} </p>
            {{!-- TODO: Fix format --}}
            <p><a href="mailto:{{post.userId.email}}"></a></p>
            <p>City: {{post.userId.address.city}} </p>
        </div>
{{/each}}

{{page-numbers content=pagedContent}}

I would extract the part you have within the <div class="listing"> into a component, roughly like this:

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

export default class Listing extends Component {
  showPost = false;

  @action
  toggleContent() {
    this.toggleProperty('showPost');
  }
}
<div class="listing">
  <h3 {{action this.toggleContent on='click'}}>{{post.title}}</h3>
  {{#if this.showPost}}
    <p>{{post.body}}</p>
    <p>User Name: {{post.userId.username}} </p>
    <p>Company: {{post.userId.company.name}}</p>
    {{!-- TODO: Fix format --}}
    <p><a href="{{post.userId.website}}"></a></p>
    <p>Catchphrase: {{post.userId.company.catchPhrase}}</p>
  
    <p>Author's Name: {{post.userId.name}} </p>
    {{!-- TODO: Fix format --}}
    <p><a href="mailto:{{post.userId.email}}"></a></p>
    <p>City: {{post.userId.address.city}} </p>
  {{/if}}
</div>

Then in your template you can use that like this:

<h2>Titles</h2>
{{outlet}}

{{#each pagedContent as |post|}}
  <Listing @post={{post}} />
{{/each}}

It’s important to note, however, that making the h3 expand like that isn’t very accessible. You may want to make it a button which is visually styled more like an h3.

1 Like

Hey, thanks for all your help. I change the module declaration from

import Component from '@ember/controller'; 

and it should have been

 import Component from '@ember/component';

Ah, that would do it! Sorry for the typo, and glad you got it sorted! I’ve updated the original so it’s not confusing for others in the future.

1 Like