NileshPatel17 / ng-multiselect-dropdown

Multiple Select Dropdown Component
https://nileshpatel17.github.io/ng-multiselect-dropdown/
327 stars 287 forks source link

How to change language with ngx-translate for text values #334

Open cyberworkz opened 3 years ago

cyberworkz commented 3 years ago

Angular version: 11

ng-multiselect-dropdown version: 4.11

Description of issue: How to change language of text fields in dropdown of multiselect with ngx-translate? Currenlty I try this but it does not work

this._onLangChange = this._translateService.onLangChange.subscribe((event: LangChangeEvent) => {
      this.dropdownSettings.textField = 'name_'.concat(event.lang);
      console.log(this.dropdownSettingsCategory.textField);
    });
Damian96 commented 2 months ago

For anyone interested, I found a workaround using the Viewchild decorator and assigning to the MultiSelectComponent.

export class MyComponent  {

  @ViewChild('filterCatsMultiSelect') filterCatsMultiSelect: MultiSelectComponent;
  categoriesDropdownList: Array<any>;
  dropdownSettings: IDropdownSettings = {
    idField: 'item_id',
    textField: 'item_text',
    ... // rest of options
  };

  ngOnInit() {
    // initialize the categoriesDropdownList with all available languages
    this.categoriesDropdownList = this.apiCategories.map((apiCat) => {
      return { item_text: apiCat.title, item_text_el: apiCat.title_el, item_text_en: apiCat.title_en, item_id: apiCat.id };
    })

    // on Language change of NGXTranslate
    this._translateService.onLangChange.subscribe((langEvent) => {

        // set the dropdown items to their translations
        this.categoriesDropdownList.set(this.categoriesDropdownList.map((item) => {
          return { ...item, item_text: item['item_text_' + langEvent.lang] };
        }));

        // change the labels of the selectedDropdownItems
        this.filterCatsMultiSelect.selectedItems = this.filterCatsMultiSelect.selectedItems.map((selectedItem) => {
          const ogItem = this.categoriesDropdownList.find((item) => item.item_id === selectedItem.id);

          return { ...selectedItem, text: ogItem['item_text_' + langEvent.lang] };
        });
      });
    }
  }
}