The issue of two-way data binding not functioning properly when using ng-select in Angular versions 9 and above has

I've encountered an issue in my Angular project where I'm trying to set a default value for the ng-select dropdown, but it doesn't seem to be working properly. The dropdown does not update when there is a change.

Let's take a look at 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>

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';

Answer №1

One potential approach could involve utilizing the @ViewChild decorator to dynamically modify the select element:

@Component({...})
export class MyCustomComponent {
  @ViewChild(NgSelectComponent, {static: true}) selectComponent: NgSelectComponent;
  ngOnInit(){
    this.selectComponent.select({ value: '1' })
  }
}

Answer №2

Have you considered initializing the defaultCountry variable like this? :

defaultCountry: any = {};

Answer №3

Oops! My mistake. I was able to figure it out in the end. By incorporating Two-Way bindings and removing formControlNames from the ng-select dropdowns, I was able to assign default values to the input fields successfully. Thank you for all the helpful responses.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service: { de49e137f2423457985ec6794536cd3c: { productId: 'de49e137f2423457985ec6794536cd3c', title: 'ite ...

Can you explain the concept of a mapped type and its practical applications?

What is the function of this? And when would be the best scenario to utilize it? ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Can you please verify the most recent updates for Bootstrap and Syncfusion in my Angular project?

Could someone help me figure out when the bootstrap and syncfusion libraries were last updated in my Angular project? I'm having difficulty finding this information. ...

Spring MVC seems to be ignoring the static resources specified in the HTML files

Currently, I am in the process of creating a straightforward Spring MVC (v4.1.2) and Angular4 application. Essentially, this application performs CRUD operations by sending HTTP requests from the Angular client. The following combination works seamlessly ...

Angular 2 Ahead-of-Time compiler: all clear on the error front, yet a nagging feeling of

I've spent the last 72 hours trying to figure out how to make Ahead-of-Time compilation work for my Angular 2 rc.6 application. Currently, my application runs smoothly using Just-in-Time compilation. I've made sure to install all necessary depe ...

The powerful combination of harp.gl and Angular NG

We've integrated harp.gl into our ng Angular application, but we're encountering issues when trying to connect to data sources that previously worked in our yarn demo. The datasource is created as follows: const dataSource = new OmvDataSour ...

Expanding code lines beyond 80 characters in Visual Studio Code with TSLint integration

I am utilizing TypeScript alongside TSLint and Prettier within Visual Studio Code for developing a React Native App. Despite my efforts to set up my editor to automatically wrap the code per line at 100 characters, it consistently reverts back to 80 chara ...

Issues Arise with Nativescript Layout When Content is Not in View on iOS

This problem has been giving me a hard time for the past few days. I hope someone can help me figure out what's wrong. I have a view that shows a nested list inside a main list. The main list contains header details. Everything looks fine when the in ...

"Enhancing asynchronous operations in rxjs: creating a forEach loop that can pause and wait

Within my foreach loop, I encountered a situation where I needed to make an HTTP request to fetch certain information. In my attempt to address this issue, I experimented with using a forkJoin within the loop to ensure that it waits for the observables (al ...

struggling to access the value of [(ngModel)] within Angular 6 component

When working in an HTML file, I am using ngModel to retrieve a value that I want to utilize in my component. edit-customer.component.html <input id="userInfoEmail" type="text" class="form-control" value="{{userInfo.email}}" [(ngModel)]="userInfo.email ...

Material-UI - TypeScript - Autocomplete utilizing getOptionLabel and renderOption for optimized selection functionality

I am attempting to showcase member and company using MUI Autocomplete. I have an array called suggestion that contains the options to display. [ { "__typename": "Member", "id": "ckwa91sfy0sd241b4l8rek ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

The RxJS Map operator may struggle to detect changes in an array that has been

EDIT: My question has been flagged as a duplicate. Despite my efforts to search for a solution, I failed to consider the full context of the issue and wasted hours using incorrect keywords. I have acknowledged the helpful response provided once the mistake ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...

Traditional method for integrating external node modules into an Angular application

I couldn't find clear guidance on this topic online. I'm trying to figure out the best method for integrating these modules into my project. One possible approach is adding them to the app.module.ts file and then importing them in the appropriate ...

Leverage the parent scope, methods, and attributes within transcluded components

I was attempting to utilize transclusion in Angular 6, but I struggled to manage my scopes correctly. <component-smart1 [someObject]="myObject" [someService]="saidService"> <component-dumb-1 [specificObject]="getSpecificObject()">&l ...