Retrieve the predetermined value from the dropdown menu option

I currently have two classes with a mapping structure as follows:

User *--------------------1 Sexe

Users are listed in the file list-users.component.html. When selecting a user for modification, I am redirected to the modify-user.component.html

Below are the necessary files: * the list-users.component.html is:

<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Sexe</th>
        </tr>
    </thead>
    <tbody *ngIf="!loader">
        <tr *ngFor="let user of userbs | async" style="width: 1500px;">
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
            <td>{{user.sexe.libelle}}</td>
        </tr>
    </tbody>
</table>

where userbs is retrieved using the service userService.getUsersList() with the type Observable<User[]>.

the modify-user.component.html is:

<form [formGroup]="editForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" formControlName="name" placeholder="Name" name="name" class="form-control" id="name">
    </div>

    <div class="form-group">
        <label for="name">Sexe</label>

        <select (change)="onChangeSexeName($event)" class="form-control select2" style="width: 100%;">
            <option *ngFor="let sexe of sexes" [ngValue]="sexe" [selected]="selected">{{sexe.name}}</option>
        </select>
        ==> Original Sexe: {{selectedSexeUserCompare.name}}
    </div>

    <button class="btn btn-success">Update</button>
</form>

and modify-user.component.ts is:

export class ModifyUserComponent implements OnInit {
    //Code snippet provided...
}

Upon visiting the modify-user page, I encounter an issue where the displayed sexe libelle does not match the correct value from the list of sexes. The discrepancy can be seen clearly in this screenshot.

If you have any insights or solutions to resolve this issue, your assistance would be greatly appreciated. Thank you.

Answer №1

It's important to make sure you include the sex field in your editForm and initialize it with the value from your localStorage.

this.editForm = this.formBuilder.group({
    sex: [selectedSexeUserCompare.num, Validators.required]
    // Add more form controls here
});

Another thing to watch out for is setting the ngValue in your options to a unique value like the num property of your sexe object instead of the entire object.

modify-user.component.html

<select formControlName="sex" (change)="onChangeSexeName($event)" class="form-control select2" style="width: 100%;">
    <option *ngFor="let sexe of sexes" [ngValue]="sexe.num">
        {{sexe.name}}
    </option>
</select>

Edit: Check out this example on StackBlitz

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

How can I retrieve specific URL parameters from the in-memory web API in Angular 2?

To retrieve data for a specific unit ID, I am using a parameter called "UnitID" in the following code: this.unitDetailsService.getUnitDetailsbyId(this.activeUnitId) I am utilizing the activeUnitId parameter to generate a URL for an in-memory service with ...

What is the reason behind the absence of compile time errors when using 'string' functions on an 'any' field type variable in TypeScript?

Looking at the following typescript code snippet: let a; a = "number"; let t = a.endsWith('r'); console.log(t); It is worth noting that since variable 'a' is not declared with a specific type, the compiler infers it as ...

Incorporate dynamic HTML into Angular by adding CSS styling

Just starting out with Angular and have limited front-end experience. I'm feeling a bit lost on how to proceed. Currently, I have a mat-table with a static datasource (will connect to a database in the future), and I need to dynamically change the bac ...

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

The assigned type 'string' for Apache ECharts does not match the expected type 'pictorialBar'

This demonstration is functional. Nevertheless, the options utilize any and my goal is to convert them to the EChartOption type. This is my current progress and the demonstration compiles successfully with this setup (With type: 'bar' commented ...

Attempting to create an interactive stepper within a material dialog using reactive forms for a versatile "smart" helper feature

Currently, I am working on developing an assistant that can display different steps based on the data it receives. This flexibility will allow me to use the assistant for various user types, each requiring a unique set of steps. For example, registration m ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Using AKS Kubernetes to access a Spring Boot application from an Angular frontend using the service name

I have developed two frontend applications using Angular and a backend application using Spring Boot. Both apps are running in the same namespace. I have already set up two services of type Loadbalancer: The frontend service is named frontend-app-lb (exp ...

Having trouble typing computed values in Vue Composition API with TypeScript?

I'm attempting to obtain a computed value using the composition API in vue, and here is the code I am working with: setup() { const store = useStore(); const spaUrls = inject<SpaUrls>('spaUrls'); const azureAd = inject<AzureAd ...

Ways to inform websocket client of authentication failure

Utilizing the (ws package) in Node.js to handle websockets, I leverage the "on upgrade" event to authenticate incoming clients based on a token provided as a URL parameter. Following the guide here, if the token is invalid/missing/expired, I utilize the fo ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Using Angular's typeahead with RxJs switchMap for subscribing to data sources

Implementing the Angular bootstrap Typeahead plugin for displaying colors. However, I am facing difficulty in resolving circular references like I have done in other parts of my project. The RxJs SwitchMap operator is not working for me in this case. Are t ...

The standard category of class method parameter nature

I'm encountering difficulties when attempting to correctly define a method within a class. To begin with, here is the initial class structure: export class Plugin { configure(config: AppConfig) {} beforeLaunch(config: AppConfig) {} afterSe ...

What function is missing from the equation?

I am encountering an issue with an object of type "user" that is supposed to have a function called "getPermission()". While running my Angular 7 application, I am getting the error message "TypeError: this.user.getPermission is not a function". Here is w ...

What is the best way to implement a singleton service throughout an Angular application?

I am currently working with a service that emits events: import { Subject, Observable } from "rxjs"; import { Injectable } from "@angular/core"; @Injectable({ providedIn: "root" }) export class TabEvents { private routeParameters: Subject<any> ...