`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The backend sends the gender in enum format; I need it to be parsed as '1' for 'Male' and '2' for 'Female'. Here is the structure of the backend data:

{
  "salesPersonId": 13,
  "name": "testName",
  "gender": 1,
  "phone1": "34986215",
  "phone2": "string",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62160711160b0c05270f030b0e22071a">[email protected]</a>",
  "team": "Bravo",
  "teamLeader": "Delta",
  "countyId": 1,
  "county": null,
  "subCountyId": 1,
  "subCounty": null,
  "address": "House 108",
  "additionalInfo": "He Drinks tea",
  "input1": "string",
  "input2": "string"
}

Here is how I am trying to bind this data:

 <mat-form-field appearance="outline" fxFlex="33" class="pr-4">
    <mat-label>Gender</mat-label>
    <mat-select formControlName="gender">
        <mat-option value="1">1</mat-option>
        <mat-option value="2">2</mat-option>

    </mat-select>
</mat-form-field>

The gender is not being pre-selected based on the back-end data received, and there are no errors thrown. Note that I am using reactive forms. Thank you in advance.

Answer №1

To utilize the setValue method within Angular Forms, follow these steps:

If you are using a FormGroup, make sure to employ the property binding for value in your HTML as demonstrated below:

<form [formGroup]="myGroup">
  <mat-form-field>
  <mat-label>Gender</mat-label>
  <mat-select formControlName="gender">
    <mat-option [value]="1">Male</mat-option>
    <mat-option [value]="2">Female</mat-option>
  </mat-select>
</mat-form-field>
</form>

Adjust your TypeScript code accordingly:

user = { "name": "testName", "gender": 1 };

ngOnInit() {
    this.myGroup.controls['gender'].setValue(this.user.gender);
}

Check out the StackBlitz Demo.

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

"Organize your files with React and TypeScript using a file list

interface IVideos { lastModified: number, name: string, path: string, size: number, type: string, webkitRelativePath: string } const [videos, setVideos] = useState<IVideos[] | null>([]); <input type="file" onChange={(event) => ...

The utilization of TypeScript featuring a variable that goes by two different names

As I dive into TypeScript code, coming from a Java background, I struggle to grasp the syntax used in this particular example. The snippet of code in question is extracted from the initial Material UI Select sample: const [labelWidth, setLabelWidth] = Rea ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

What is the process for incorporating a manually created Angular package into a project as a node modules package?

Looking for help on integrating a custom-built package into an Angular project instead of the default one installed via npm. I attempted to replace the original package in node_modules with my custom build, but encountered issues. The specific package I& ...

Is there a way to modify the login component to utilize the username instead of the email for logging in?

I recently developed a Spring Boot API which requires the username and password for login authentication. I am now trying to modify the ngx admin interface to accept the username instead of the email as the credential. Can anyone provide guidance on how ...

Encountering an issue when retrieving the value from a template-driven Angular form

Encountering an issue in the register function regarding storing the form control value. When using "let firstname", "let lastname", and "let email", I am receiving the error [tslint] Identifier 'firstName' is never reassigned; use 'const&a ...

Encountering difficulties when attempting to globally install Angular CLI on Node.js version 18.15.0

Encountering an issue while setting up the latest version of Angular using NVM and the most recent Node.js version After installing Node.js version 18.15.0, I attempted to run npm i -g @angular/cli Unfortunately, I received the error below. Has anyone el ...

Activating functions based on radio button selection in React with TypeScript

Below are the radio buttons with their respective functions: <div className="row"> <div className="col-md-4"> <label className="radio"> <input onChange={() => {serviceCalc()}} ty ...

Whenever the [required] tag switches from being true to false, it generates an event

Initially, I have set up an Angular form using the following code snippet buildForm() { this.form = this.formBuilder.group({ value1: this.formBuilder.control(null), value2: this.formBuilder.control(false) }); } The HTML contains a ...

Out with TSLint, in with ESLint: Upgrading our code quality tool

I have been working on a project in Angular 10 that was recently upgraded to Angular 12. With the upgrade, TSLint is no longer used in Angular 12, but remnants of it still exist in the project, such as the tslint.json file and associated packages. How ca ...

Tips for sending an Angular http post request including both data and an image:

When making a post request in Angular, I typically send data (such as 'product' data) using an object like this: product: any = {}; // filled with properties (code, barcode, name, description...) and then include it in the request: return this.h ...

Unable to access pathways from a separate source

In my app.component.ts file, I have two router outlets defined, one with the name 'popup': @Component({ selector: 'app-main', template: `<router-outlet></router-outlet> <router-outlet name="popup" ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

Issues with the messaging functionality of socket.io

Utilizing socket.io and socket.io-client, I have set up a chat system for users and operators. The connections are established successfully, but I am encountering strange behavior when it comes to sending messages. For instance, when I send a message from ...

Best practice for importing pipeable RxJs operators in Angular CLI/WebPack rollup

In the earlier versions of Angular CLI, specifically those before 1.5.0, it was common practice to import all RxJs operators and statics into a single file for easy usage throughout the application. For example: rxjs-operators.ts // Statics import &apos ...

Implementing generics in TypeScript for objects made easy with this guide!

My question is regarding a function that utilizes generics and selects data from an object based on a key. Can we use generics inside the type of this object, or do we have to create a separate function for options? enum Types { book = 'book', ...

What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object? For instance, in ES5 you can achieve the following: const person = { firstName: "John", lastName: "Doe", get fullName() {return `${this.firstName} ${this.lastName}`} } person.fullNam ...

Angular 2: A helpful guide on how to duplicate an object within another object

I'm seeking assistance on how to duplicate an object into another object using Angular 2. Previously in Angular, I utilized angular.copy() to duplicate objects to the vague reference of the original ones. However, when attempting the same in Angular ...

Store a new JSON item in the localStorage

Currently, I am tackling a task in Angular where the objective is to store items to be purchased in localStorage before adding them to the cart. There are four distinct objects that users can add, and an item can be added multiple times. The rule is to ch ...