[Fixed] Two way data binding is not working with ng-select in angular 9+

Issue

I am working on an angular project where I need to assign a default value to the ng-select dropdown, but it is not working, and not updating on the dropdown change.

here is the code.

template code

  <ng-select
  [items]="countries"
  class="text-capitalize"
  bindValue="id"
  [closeOnSelect]="true"
  [(ngModel)]="defaultCountry"
  [searchable]="true"
  (change)="changeCountry($event)"
  placeholder="{{
    _translate.currentLang == 'en'
      ? 'Country'
      : _translate.currentLang == 'ps'
      ? 'هیواد'
      : 'کشور'
  }}"
  [formControlName]="countryControlName"
>
  <ng-template ng-label-tmp let-item="item">
    {{
      _translate.currentLang == "en"
        ? item.label_en
        : _translate.currentLang == "ps"
        ? item.label_ps
        : item.label_fa
    }}
  </ng-template>
  <ng-template ng-option-tmp let-item="item">
    {{
      _translate.currentLang == "en"
        ? item.label_en
        : _translate.currentLang == "ps"
        ? item.label_ps
        : item.label_fa
    }}
  </ng-template>
</ng-select>

here is the typescript code

defaultCountry:any;

 this.countries = [ {id: "1", label_en: "Afghanistan", label_ps: "افغانستان", label_fa: "افغانستان", value: "Afghanistan"},
 {id: "3", label_ps: "البانیا", label_fa: "البانیا", label_en: "Albania", value: "Albania"},
 {id: "3", label_ps: "الجزایر", label_fa: "الجزایر", label_en: "Algeria", value: "Algeria"}];


 this.defaultCountry = '1';

Solution

Oh my bad!
I managed to solve it finally.
I used Two-Way bindings as well as formControlNames in the ng-select dropdowns, which was preventing the default values to be assigned to the input fields. when I removed the control names it did work.
thanks for the efforts of posting answers.

Leave a Reply

(*) Required, Your email will not be published