Search code examples
ember.jsember-cliember.js-2

Ember 2 - Hide / show content component


I have a component app/components/offer-listing.js:

import Ember from 'ember';

export default Ember.Component.extend({
  isOfferShowing: false,
  actions: {
    offerShow() {
      if (this.get('isOfferShowing')) {
        this.set('isOfferShowing', false);
      } else {
        this.set('isOfferShowing', true);
      }
    }
  }
});

and his template app/templates/components/offer-listing.hbs:

<div class="offer__container">
  <div class="row">
    <div class="gr-3">
      <div class="offer__avatar" style="background-image: url('{{ offer.avatar }}')"></div>
    </div>
    <div class="gr-9">
      <div class="offer__name" {{action "offerShow"}}>{{ offer.firstname }} {{ offer.lastname }}</div>
      <div class="offer__age" {{action "offerShow"}}>{{ offer.age }} ans</div>
      {{#if isOfferShowing}}
        <div class="offer__description" {{action "offerShow"}}>{{offer.description}}</div>
      {{else}}
        <div class="offer__description" {{action "offerShow"}}>{{word-limit offer.description 50}}</div>
      {{/if}}

      {{#if isOfferShowing}}
        <div class="+spacer"></div>
        <a class="offer__button"><i class="fa fa-envelope"></i> Contacter par email</a>
        <a class="offer__button"><i class="fa fa-phone"></i> Voir le numéro de téléphone</a>
      {{/if}}
    </div>
  </div>
</div>

which is rendered in app/templates/index.hbs:

{{#each model as |offerUnit|}}
  {{offer-listing offer=offerUnit}}
{{/each}}

The example is working great, however I would like to hide every "more" content when a new one is showing.


Solution

  • A working solution for this is available here : Using Ember component's methods inside template

    Basically, either you keep a reference to the selected element in your controller and pass it to each of your offer-listing components. This way they could compare themselves with this reference to known if they need to be displayed or not.

    Or you set a flag in each of your offer model depending on whether is needs to be displayed or not.