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

Developing a cutting-edge project: Integrating Angular with PrimeNG to create a dynamic Sakai skeleton demo

I have just cloned the Sakai angular skeleton repository from this location: git clone https://github.com/primefaces/sakai-ng.git In the default setup, the 'landing' URL is set to the Sakai demo. However, I would like my base URL to point to my ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

What could be causing the .env.development file to malfunction in my Next.js application?

I am currently working on Jest and testing library tests. Let's discuss a component named BenchmarksPage. Please pay attention to the first line in its return statement. import { Box, capitalize, Container, FormControl, InputLabel, MenuI ...

Discovering the Best Way to Display Node.js API Errors in an Angular Application

When encountering an error in my Node.js application, I handle it like so: app.get('/api/login', (req, res, next) => { //... return res.status(400).send({ isSuccess: false, errors: ["error 1", "error 2"] }) }) Now ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

Tips for adjusting the maximum characters per line in tinyMCE 5.0.11

I have an angular 8 application that utilizes tinyMCE, and I am looking to limit the maximum number of characters per line in the textArea of tinyMCE. My search for a solution has been unsuccessful so far despite extensive googling efforts. (image link: [ ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

Infragistics: A guide to displaying numerous ignite Snackbar instances with unique identifiers

I am trying to display multiple Snackbars on my Angular website. I'm utilizing Ignite UI for Angular and incorporating the Snackbar feature from Ignite. <igx-snackbar id="snackbar1" [displayTime]="displayTime"> <div [cla ...

Error TS2322: Cannot assign type 'Foo | Bar' to type 'Foo & Bar'

I am attempting to save an item in an object using the object key as the discriminator for the type. Refer to the edit below. Below is a simple example: type Foo = { id: 'foo' } type Bar = { id: 'bar' } type Container = { foo ...

ngIf is not refreshing my template

Within my Angular2 application, I have a Component that takes an array as input and utilizes a service to retrieve the Latitude and Longitude for each entry in the array. This involves making multiple asynchronous calls to the service using Promises. expo ...

Flashing Screens with Ionic 2

I am currently dealing with a situation where my login page and homepage are involved. I have implemented native storage to set an item that helps in checking if the user is already logged in (either through Facebook or Google authentication). The logic fo ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Leverage the power of Firebase Firestore by seamlessly integrating full-text search capabilities with external services while also

While I understand that using external services like Algolia and Elasticsearch is necessary for full-text queries in Firestore, my struggle lies in integrating these tools with Firestore's existing querying options such as "where," "limit," and "start ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Using Angular to pass a class as a parameter in an HTTP GET request

I am currently working with a class that looks like this: export class CodeTable { public tableId: number; public connectionTable: number; public connectionCode: number; public code: number; ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

Encountered an error while trying to run the command "lite-server" in Angular 2

I recently had a machine where I installed Zsh and OhMyZsh, but later on uninstalled them. However, now whenever I try to run "npm start" on the Angular 2 Quick Starter template, I keep encountering this error message: Error occurred when executing comma ...

Assign a class to an Angular component's host element without any conditions

In my Angular project, I have a component where I need to apply a class unconditionally. To achieve this, the host property within the @Component decorator can be used: import { Component } from '@angular/core'; @Component({ selector: 'ap ...