Assign the chosen value to the dropdown list if ngModel is present

I currently have a select field implemented in my Angular component:

<select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states" 
      [ngValue]="state">
       {{state.name}}</option>
</select>

As I'm using this component in multiple places, I'm looking for a way to set the selected option based on the value of my ngModel. If, for instance,

myClient.address = {"name":"Texas", "stateId":"2"}
, then Texas should be pre-selected in the dropdown menu.

Is there a method to achieve this functionality?

Answer №1

<select class="form-control" [ngModel]="myCustomer.location?.city" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let city of cities" 
      [ngValue]="city">
       {{city.name}}</option>
</select>

Assuming myCustomer.location is defined as

myCustomer.location = {"city":"New York", "cityId":"5"}
, New York will be automatically selected in the dropdown.

If you want to make the selection optional, simply add a question mark before the property like this:

[ngModel]="myCustomer.location?.city"
. This way, if the value is present it will be selected, otherwise nothing will be pre-selected.

Just make sure to provide the myCustomer.location object with or without values for the functionality to work properly.

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

Issue with Angular 6 and Html Webpack Plugin

My project was recently updated from Angular 5 to Angular 6, causing some changes in the file structure. The webpack.config files are no longer present and the project now operates under CLI engage. However, I encountered an issue after the migration rela ...

Cease the animated loading icon once the template has finished loading in sync with the async pipe

.ts initialize() { const loadingScreen = await this.loadingService.displayLoader();//loading screen this.products$ = this.bikeShopService.retrieveData();//Observable operation } .html <ion-col size="6" *ngFor="let product of (products$ ...

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

Ensuring Generics are Required in your Code

Can Generics be marked as mandatory in typescript? function validateGenerics<Result, Variables>({ foo, bar }: { foo: Result bar: Variables }) { console.log(foo, bar) } // Attempting to call the function without passing Gener ...

The event triggered by the tinymce editor does not immediately refresh the Angular Component

I am currently working on creating an Angular application using a WordPress instance of TinyMCE. Within the editor, there are non-content-editable elements that trigger a modal window to open when clicked. However, I have encountered an issue where the mo ...

Enhance the variety of types for an external module in TypeScript

I am in the process of migrating an existing codebase from a JavaScript/React/JSX setup to TypeScript. My plan is to tackle this task file by file, but I have a question regarding the best approach to make the TypeScript compiler work seamlessly with the e ...

Angular's Mysterious Pipe

When navigating to the indice page, I want to adjust the number formatting in the cours column to display two decimal places. For instance: 11345.654589 should be displayed as 11345.65. https://i.stack.imgur.com/tjvWb.png To achieve this, I have created ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

Encountering an issue while attempting to make an in-app purchase with Ionic 3 and Cordova - receiving the error message "Sorry, the item you are trying to

In the process of developing my app with IONIC 3 and Angular 4, I have integrated the following Ionic plugin for in-app purchases: https://ionicframework.com/docs/native/in-app-purchase/ Once the plugin was installed, I included the "play_store_key" in t ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Method for Injecting Global Constants Provider in Angular 2

I am trying to implement a global constants setup in my Angular app, specifically with a root directory that should be accessible to every component without the need for manual imports. I came across a solution on Stack Overflow suggesting the use of a con ...

Discovering the true nature of a generic Type in TypeScript

Consider this scenario involving TypeScript interface IApiCall<TResponse> { method: string; url: string; } Above interface is utilized in the following method; const call = <TResponse>(api: IApiCall<TResponse>): void => { ...

Following the update, Angular no longer requires any node dependencies

Recently upgraded from Angular 5 to 9 and encountered an error in the browser's devtools: Uncaught ReferenceError: global is not defined After researching, I found a helpful post that discusses the issue: Upgrading to angular-6.x gives "Unca ...

What is the relevance of `type Constructor<T> = Function & { prototype: T }` in relation to Abstract constructor types in TypeScript?

Can anyone help me understand how to use the Abstract constructor types in TypeScript? I came across this question and answer on Stack Overflow regarding the topic: Abstract constructor type in TypeScript The accepted answer provided a one-liner code sni ...

What is the best way to switch to a different screen in a React Native application?

I've recently dived into the world of React Native and embarked on a new project. The initial screen that greets users upon launching the app is the "welcome screen," complete with a prominent 'continue' button. Ideally, clicking this button ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Steps for setting up an auth guard:1. Define a

I am facing an issue with implementing two guards in my Angular application. The first guard is supposed to restrict unauthorized users from accessing certain pages, while the second guard is meant to prevent authorized users from accessing the "sign-in" a ...

Angular 2: It is essential to have a distinct instance for Signature Pad

I am seeking assistance with utilizing the signature pad feature in order to capture multiple signatures. Below is a snippet of my code. I have 'n' number of employees and would like each employee to input their signature into the designated box ...