Choose the Angular 2 option

I am having an issue with the select option in my code. The person's gender property is assigned 'M' for male, but I need to allow users to change it to 'F' for female.

Here is the HTML code snippet:

<span >
    <span >
        <span >Gender</span>
        <span ></span>
        <select name='gender'>
            <option [value]='' selected>{{entity.person.sex}}</option>
            <option [ngValue]="">{{}}</option>
        </select>
    </span>
</span>

Answer №1

Ensure to call a function when the event is triggered:

 <select name='gender' (change)="selectChangeHandler($event)">
      <option ....
 </select>

Function in Component:

selectChangeHandler (event: any) {
    //update the user interface
    this.entity.person.sex = event.target.value;
  }

Answer №2

If you want to go the angular route, I suggest binding the select element to your model.

Here is how you can set it up in your HTML file (...component.html):

    <span>
        <span>
            <span>Gender</span>
            <select name='gender' [(ngModel)]="entity.person.sex">
                <option value='M'>Male</option>
                <option value='F'>Female</option>
            </select>
        </span>
    </span>

In your TypeScript file (...component.ts):

export class AppComponent  {
  entity =  {
    person: {
      sex: 'M'
    }
  };
  // add the rest of your component here...
}

Feel free to check out this StackBlitz demo to experiment with it yourself.

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

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

Guide to creating a generic that captures the prop types of a given component

Is there a way to create a function that accepts a component and uses its prop type as the type of the second parameter? For example, if I provide a component with the type React.FunctionComponent<IMovieShowcase> How would I go about extracting the ...

Implementing conditions in Angular2 router

Here are my current routes: const appRoutes: Routes = [ { path: 'alert/:id', component: AlertDetailComponent }, { path: 'alerts', component: AlertsComponent }, { path: 'dashboard', component: EriskDashboardComponent }, { pa ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

Tips for deploying an Angular 6 application on a Node server

I am working on an Angular 6 application that needs to be served by a Node server running on port 8080. After some research, I found that adding a server.js file with certain configurations can help achieve this. However, I am unsure about how to modify th ...

What to do when Observable fails to close due to an error?

Consider the following code snippet: Observable.timer(0, 10000) .switchMap(() => this.http.get(url)) .retryWhen(errors => errors.delay(10000)) .subscribe(data => displayData(data)) This code ensures that an HTTP call is made every 10 seconds wit ...

The element 'mat-tab' does not recognize the property 'active', therefore it cannot be bound

I keep encountering this error even though I have already imported MatTabsModule. Below is the structure of my component: @Component({ selector: 'app-settings-page', template: ` <mat-tab-group animationDuration="0ms"> <mat-tab *n ...

Sending properties via react router link in TypeScript

I have successfully defined my routes and made my links functional. I am now trying to figure out how to pass a prop through the link when the component is called by the router. It seems like a challenging task. To understand better, take a look at this c ...

The TypeScript declarations for the scss module are malfunctioning

Just recently, I set up a React project using rollup. Below is the configuration file for my rollup setup: rollup.config.js import serve from "rollup-plugin-serve"; import livereload from "rollup-plugin-livereload"; import babel from &q ...

Just recently updated to Angular 14 and I'm encountering a problem with images not loading from the assets folder. I'm wondering if there is a configuration step I missed. Could someone please

https://i.stack.imgur.com/4LEQ4.png https://i.stack.imgur.com/3sxzF.png Is there a configuration missing in Angular 14? When I try using <img [src]="assets/images/sidebarNav"> with ./, ../, it doesn't work. I have followed the instr ...

Troubleshooting issues when integrating three.js GLTFLoader() with TypeScript due to conflicts with zimjs

Successfully loading a model using three.js GLTFLoader() with TypeScript in a nuxt.js application: this.mGLTFLoader = new (<any>THREE).GLTFLoader(); this.mGLTFLoader.load(pPath, (gltf) => this.onLoad(gltf), (xhr) => this.onProgress(xhr), (e) = ...

Create a Typescript type extension specifically designed for objects with nested arrays of objects

After stumbling upon this inquiry, I am eager to adjust my code in a similar fashion, utilizing typescript and a more intricate object. Consider the type below: export type ImportationType = { commercialImportation: boolean dateToManufacturer: string ...

Leveraging the expand function for pagination through recursive invocations

I am currently working on retrieving data from a third party API that necessitates manual management of paging by keeping track of the number of records retrieved versus the total number of records available. In attempting to handle this, I experimented w ...

Put Jest to the test by testing the appendFileSync function

I am currently working on creating a test for appendfilesync function. When using a logger, I noticed that one line of code is not covered in my tests. Below is the code snippet I am referring to (please note that I am using tslog for logging purposes): ex ...

Exploring the Ways to Determine Array Type in Typescript Generics

I'm working with a method that looks like this: public select(fieldName: keyof TType) In this scenario, TType can potentially be an array type. If fieldName is called with a type of User[], I want to access the properties of User instead of the defa ...

Various modules in the project need to have distinct GitHub origins, particularly in the case of Spring-Angular

My goal is to create a well-structured project with separate frontend and backend modules. Here is the initial project structure: https://i.stack.imgur.com/EghPA.png I have attempted this in various configurations before, but every time I try, git recogn ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

What could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

No errors found on minikube for the Angular app, just a blank page displayed

I recently created an Angular application and successfully built the image using Docker: # stage 1 FROM node:10-alpine as node WORKDIR /app COPY package*.json /app/ RUN npm install COPY ./ /app/ RUN npm run build # stage 2 FROM nginx:1.17-alpine COPY ...

React's setState function failed to update the specified value within the set

In attempting to update the state values, I encountered an issue where the state did not get updated as expected. To troubleshoot, I included console logs at each line of code. handleFilter=(event)=> { console.log(this.state.answerStatus) // In ...