Navigating nested data structures in reactive forms

When performing a POST request, we often create something similar to:

const userData = this.userForm.value;

Imagine you have the following template:

<input type="text" id="userName" formControlName="userName">
<input type="email" id="userEmail" formControlName="userEmail">
<select id="userTypeId" formControlName="userTypeId">
  <option *ngFor="let userType of userTypes" [value]="userType.id">{{userType.name}}</option>
</select>

In your userData, the values will be:

{
  userName: 'foo',
  userEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40262f2f002221326e232f2d">[email protected]</a>',
  userTypeId: '1'
}

However, your API expects:

{
  userName: string,
  userEmail: string,
  userType: UserType
}

where UserType is defined as:

{
  id: string,
  name: string,
}

To accommodate the API's model, you would need to structure it like:

const userForAPI = {
    userName: userData.userName,
    userEmail: userData.userEmail,
    userType: { id: userData.userTypeId }
}

Then you would call:

this.userService.createUser(userForAPI)

Is there an alternative solution that doesn't involve specifying { id: userData.userTypeId }? Can the template be modeled based on the API's requirements so that this.userForm.value can be directly sent to the API?

Answer №1

When working with the select/option control, you have the flexibility to set custom objects as values instead of just strings by using ngValue instead of value. This allows you to update your model to utilize userType rather than userTypeId.

<select id="userType" formControlName="userType">
  <option *ngFor="let userType of userTypes" [ngValue]="userType">{{userType.name}}</option>
</select>

Your model will now contain data similar to the following example.

{
  userName: 'foo',
  userEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88e8787a88a899ac68b8785">[email protected]</a>',
  userType: {id: '1', name: 'foo1'},
}

Take a look at this demonstration.

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

Using methods from one component in another with NgModules

There are two modules in my project, a root module and a shared module. Below is the code for the shared module: import { NgModule } from '@angular/core'; import { SomeComponent } from "./somecomponent"; @NgModule({ declarations: [SomeCompon ...

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Tips for creating type-safe assertion functions in TypeScript

In TypeScript 3.7, a new feature allows the writing of "assertion functions." One example is shown below: export type TOfferAttrName = keyof typeof offerAttrMap; export const assertIsOfferAttrName = (name: string): asserts name is TOfferAttrName => { ...

Angular Error: Unable to process _this.handler.handle as a function

While running my tests in Angular, I encountered an error: TypeError: _this.handler.handle is not a function at MergeMapSubscriber.project (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/common/esm5/http.js:1464:80) at MergeM ...

Displaying data from a service on an Ionic screen: a comprehensive guide

I've retrieved JSON data from an API: { "userGroups":[ {"title":"group 1"}, {"title":"group 2"}, {"title":"group 3"}, {"title":"group 4"} ] } Currently, I am storing this raw data in NativeStorage. // userService this.userGroup ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

Can we modify the auto-import format from `~/directory/file` to `@/directory/file`?

I have a small issue that's been bugging me. I'm working on a project using Nuxt3 and Vscode. When something is auto-imported, Vscode uses the ~/directory/file prefix instead of the preferred @/directory/file. Is there an easy way to configure Vs ...

Encountering an issue during Angular installation, which is resulting in an error message and preventing the

Whenever I attempt to install the Angular CLI using the command below: npm install -g @angular/cli An error message pops up, displaying: rollbackFailedOptional: verb npm-session 1a71d92fb103bc6 I'm puzzled as to why this issue is happening and ho ...

Exploring Vue 3: Crafting a custom plugin using the composition API and enhancing it with Typescript type augmentation

Encountering an issue with displaying plugins properly within <script> and <template> tags on WebStorm. Firstly, let's take a look at my files and configuration: tsconfig.config.json { "extends": "@vue/tsconfig/tsconfig. ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

Discovering the process of extracting information from an individual object within a local JSON file on a detailed page using Angular 9

Here is a JSON object I am working with: [ { "products": [ { "id": "1", "name": "Apple", "price": "free", "imageURL": "assets/apples.jpg", "category": "Fruits" }, an ...

Customize the color of the Material-UI Rating Component according to its value

Objective I want to dynamically change the color of individual star icons in a Ratings component (from material-ui) based on the value selected or hovered over. For example, hovering over the 1st star would turn it red, and hovering over the 5th star woul ...

Accessing URL fragments in Next JS with context during the execution of getServerSideProps

I am trying to extract a URL fragment using getServerSideProps. The URL is structured like this: http://localhost:3000/some-folder#desiredParam=value Even though I pass the context as an argument to the getServerSideProps function, I am struggling to retr ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

Having trouble importing modules from @types/node

Currently, I am in the process of developing an Electron application with Angular. My goal is to gather information about my PC and execute certain commands within the app. I have been attempting to utilize the os and child_process modules, but unfortunate ...

Retrieve the file using GraphQL resolve

Currently, I am developing an application utilizing these technologies: Backend: Mongoose Express Apollo GraphQL Frontend: Vuejs Apollo GraphQL I have managed to s ...

Starting the process of configuring Angular 5 with Express using TypeScript

Hi there! I am looking to create a fresh application using angular 5 and express (typescript for express as well). Do you have any helpful guides or tips that could assist me in reaching my objective? Appreciate all the help, Giuseppe ...