Is there a way for me to retrieve the username of an object from a select list?

I am working with a select list that contains names, and I need to extract the name instead of the ID in order to insert it into the database. Below is my TypeScript file:

  selectUser() {
    this.UtilisateurService.findAll().then((res) => {
      let id = '';
      this.listUser = res.map(function (obj: any) {
        return {
          id: obj.id,
          text: obj.username,
        };
      });
      this.listUser.splice(0, 0, {
        id: 'empty',
        text: '-'
      });
      if (id !== '') {
        this.idUser = id;
 
      }
    });
  } 

// I want to set the value of this.nameUser as obj.username:

  nameUser:string;

 onSubmit() {
    this.submitted = true;
    if(this.messageForm.valid) {
      this.success = true;
      let obj = this.messageForm.value;
      obj.id_examen = this.idExamen;
      obj.id_coach=sessionStorage.getItem('id');
      obj.id_cible=this.idUser;
     -------> obj.username=this.nameUser;
 
        this.coachingService.addLigneExamen(obj).then(res => {
          if (res === true) {
            this.closemodal()
          }
          this.closemodal()
        });
    }
  }

Answer №1

Your task is to locate a specific user's ID within a list of users.

obj.username = this.listuser.find(user => user.id === this.idUser).text

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

Can one inherit under specific conditions?

I have just started exploring the OOP paradigm and I am curious to know if it is possible to have conditional inheritance in TypeScript. This would help avoid repeating code. Here is what I have in mind. Any suggestions or recommendations are greatly appre ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

Angular 2 - ERROR: The value of 'ngClassUntouched' expression has been modified after the initial check

The error message is as follows: angular2.dev.js:23597 EXCEPTION: Expression 'ngClassUntouched in myComponent@7:12' has been modified after it was checked. Previous value: 'true'. Current value: 'false' in [ngClassUntouched ...

How can ngx-modals detect when the modals have been closed?

I have integrated ngx-modals into my project and I am looking to add a boolean value to it. When the modals open, I want to set this boolean to "true", and when they close, I need it to be set to "false". Regardless of whether the modal is closed using the ...

Angular 2: Embracing the Power of Hierarchical Selection

My goal is to create cascading selects where each option in a dropdown menu can lead to its own set of unique child options. This will result in a hierarchical structure of selectable items. To accomplish this, I have defined a class named fieldSelect tha ...

activating a component by interacting with another component

How can I pass the uuid from parent to child component through a click event in Angular? App.component.ts import { Component } from '@angular/core'; import { v4 as uuid } from 'uuid'; @Component({ selector: 'my-app', tem ...

Having trouble importing or resolving files with ts-loader or css-loader?

Struggling to incorporate css modules by utilizing style-loader and css-loader in my project. I am facing difficulties understanding the root cause, unsure if it's ts-loader or css-loader to blame. webpack.config.js const path = require('path&a ...

Vue Basic Components 'T' has not been declared

After updating to Vue 3.4.30, I encountered an issue while trying to use Generic components. When attempting to use T as a type for a property, I received an error message. Any guidance or suggestions on how to resolve this would be greatly appreciated. I ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

The return type is not undefined but the switch covers all possibilities

I'm struggling to understand the issue with this simple example interface List { "A": false, "B": false, } // The function is missing a return statement and its return type does not include 'undefined'.ts(2366) / ...

Utilizing Services in Angular 2

I am new to learning angular2 and encountering an issue with calling a service. The service call is successful, but I am unsure how to handle the data. In Angular1, we would handle it like this: DemoService.getExchangeDataConnection().then(function(respon ...

Issue arises with library dependencies: various libraries are reliant on distinct versions of a shared library

I have multiple libraries that are dependent on the webpack library. Currently, I am using version 4.79.1, but when I run `npm install` I receive the following warning: [email protected] requires a peer of webpack@^2.0.0 || ^3.0.0 but none is in ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

Encountering a compilation error while compiling using Angular Ivy

Encountering a compile time error in my Angular 8 project when enabling angular Ivy. Upgrading to version 8.1.0 did not solve the issue, and I continue to receive the following error: D:\Users\Backup>ng build shared Building Angular Package B ...

Issue with useEffect() not receiving prop

Currently diving into the world of React and still in the learning process. I recently integrated a useEffect() hook in my code: import { fetchDetails } from "../../ApiServices/Details"; export interface RemoveModalProps { id: number; i ...

In Angular 15, CSS override configurations do not function as intended

Exploring the world of Angular is exciting, and I am a newcomer to it. Currently, I am tackling an innovative Angular 15 project that makes use of the Material library. My current predicament lies in the fact that none of the CSS overrides appear to be tak ...

Is it possible to utilize two ngForm elements within the same component in Angular 4?

Currently, I am in the process of creating a settings page that includes both profile update and password update forms. My goal is to have these two different forms within the same component. Is it feasible to integrate two form elements into one compone ...

How to access properties of objects within an array in Angular 4

Is there a method to call only the $values from each rate record in my array that I want to read? This is what I have done to access this array: async ngOnInit() { this.product$ = await this.reviewService.getReview(this.product.$key); this.key = ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

Angular reactive form validation ensures user inputs are accurate and complete before submitting

Within my reactive Angular form, I have a specific field that requires validation. In my service class, I am currently utilizing the default Validators.required function provided by Angular in the following code snippet: Countrycode: new FormControl(&apos ...