javascriptember.jsember-dataember-addon

How to pass a function in selected from ember-power-select


I have an Ember.js application, and for a form in it, I am using ember-power-select. I already used that addon, but I have some problems with how to configure the selected element. As the title say, I am asking for help with how to configure the selected with a function.
I want to set the selected variable with a function that retrieve a variable from a services.

My component look like that:

import Ember from 'ember'; 

export default Ember.Component.
    appInfo: Ember.inject.service('app-info'),

    languageOption: ['Français', 'English'],
    language() {
       /*
       * In my service appInfo, I have a function called getLocale
       * that return the current locale variable.  
       */
       return this.get('appInfo').getLocale();
       },

       actions: {
           changeLanguage(lang)
           {
              this.set('language', lang);
           }
        }
});

And my template look like that:

{{#power-select
          selected=language
          options=languageOption
          searchEnabled=false
          onchange=(action 'changeLanguage')
          placeholder=language
        as |lang|}}
          {{lang}}
{{/power-select}}

As you can see I'm trying to set my selected value with the current locale obtained via the service appInfo. Everything is working just fine except the selected part.
In the template, you can see that 'selected' is a value that can be set within a component, except that I don't want to set the value with a hardcoded one, but with the current value of locale.
Every tips and/or help is appreciated!


Solution

  • Just solved it, I used init() to make it work. As @BrandonW said in the comment, a computed property doesn't work too.

    This is the code that I putted in my component:

    ***
       init() {
            this._super(...arguments);
            let loc = this.get('appInfo').getLocale();
            if (loc === 'fr')
                this.set('language', 'Français');
            else
                this.set('language', 'English');
        }
    ***
    

    This is what you want to do if you want to use a function to set selected in ember-power-select addon.