Utilizing Angular 2: Implementing a template-driven form to send data from a chosen element to the submitting object

Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface:

export interface UserModel{
  name: string,
  service: Service
}

I've got an array of services and a form for creating a new User.

<form #f="ngForm" (submit)="addUser(f.value,f.valid)">
    <label for="name" class="col-sm-1 control-label">Name</label>
    <div class="col-sm-4">
        <input class="form-control" [(ngModel)]="userModel.name" #name="ngModel" name="name" ng-maxlength="49" />
    </div>
    <label class="col-sm-1 control-label">Service</label>
        <select class="form-control" name="service" [(ngModel)]="userModel.service">
            <option *ngFor='let service of services' [value]='service'>{{service.name}}</option>
        </select>
    </div>
    <button class="btn btn-primary" type="submit">Create</button>
</form>

I'm struggling with how to pass the selected service object to the User object. When I try it this way, I end up with:

Object{
  "name": "something",
  "service": "[Object object]"
}

It's clear that passing an object as the value to the select element doesn't work. So, I decided to set the value to the id of the Service instead and modified the interface:

export interface UserModel{
   name: string,
   serviceId: number
}

Prior to submission, I find the Service object based on its id in the array of services and set it in the User object along with the Service object inside.

userModel: UserModel;
user: User;

submit(model: UserModel ){
   this.user = {
     name : model.name,
     service: this.findService(model.serviceId) 
  }
}



ngOnInti(){
 this.userModel= <userModel>{};
}

Does this approach seem effective? Are there better ways to handle this situation? This is just a snippet of (handwritten) code that represents a working example. Thanks!

Answer №1

The reason it saved [Object object] is because the value attribute in your code does a stringify of the object. If you intend to save an Object value when an option is selected, you should use [ngValue] instead of [value]. The [ngValue] property effectively maintains and retains the object value.

Example

<select class="form-control" name="service" [(ngModel)]="userModel.service">
  <option *ngFor='let service of services' [ngValue]='service'>
     {{service.name}}
  </option>
</select>

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

Transferring data from a child component to a parent component in Vue without the need for a click

In my Vue project, I have a parent component called ChangeInfo which contains a child component named ShowWorkInfo. The ShowWorkInfo component includes several input forms for updating job information. To manage the data input, I created an object variable ...

conceal a div in Angular when the user is authenticated

One of my tasks involves managing the visibility of a div based on whether the user is logged in. This functionality is achieved by utilizing an authentication service in Angular and tokens from Django. Component.html <a *ngIf="authService.isLoggedIn( ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

It appears that the blob data is not being received in the message sent from the websocket server to my Angular 2 Observable

Having trouble converting some html/javascript to Angular 2 and encountering an issue with blob data not being received in messages from the websocket host to the Angular 2 Observable. Text messages are being sent successfully from the websocket host, but ...

Alternatives to using wildcards in TypeScript

In my code, I have defined an interface called ColumnDef which consists of two methods: getValue that returns type C and getComponent which takes an input argument of type C. Everything is functioning properly as intended. interface ColumnDef<R, C> { ...

Angular 10 is not displaying images despite receiving the image path from an API

Despite my API returning the image path for the product, my Angular application is not displaying the image. HTML Code <ng-container *ngFor="let prod of productData"> <div class="row p-2 bg-white border rounded" styl ...

Deploying Firebase functions results in an error

Just recently started exploring Firebase functions. Managed to install it on my computer, but running into an error when trying to execute: === Deploying to 'app'... i deploying firestore, functions Running command: npm --prefix "$RESOURCE_ ...

Having issues with *ngFor in Angular when trying to retrieve data from an API

I have been working on fetching data from an API and displaying it on the frontend, but I am facing an issue with *ngFor. Even though all variables seem to be set up correctly and I can see the data in the console.log, it is not showing up on the frontend. ...

Accessing and manipulating a intricate JSON structure within an Ionic 3 framework to seamlessly connect it to the user

I'm currently developing an app using Ionic 3. Within my project, I have a JSON object structured like this: { "player": { "username": "thelegend", "platform": "xbox", "stats": { "normal": { "shots ...

Getting the parent from a child in Typescript: Best Practices

Querying: In TypeScript, is it possible to retrieve a parent instance from a child instance? I am aware that casting a child into its parent is a method, however, the child's additional properties still exist in the parent, albeit concealed. Check o ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

Challenges when building a production version of an Expo app with Typescript

Attempting to perform a local production build, I ran expo start --no-dev --minify. Only the initial template file displays, stating "Open up App.tsx to start working on your app," and none of my work is visible... Has anyone else encountered this issue a ...

Tips for invoking a function on a react-bootstrap-table component using TypeScript

One issue I'm encountering is trying to cast the "any" bootstrapTableRef to react-bootstrap-table, setting up the ref correctly, or importing it incorrectly. I am struggling to access the method of the imported table. While I found a solution using th ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

The FullCalendarModule does not have a property named 'registerPlugins' in its type definition

Currently in the process of integrating fullcalendar into my Angular 15 project and encountering the following error: Error: src/app/views/pages/takvim/takvim.module.ts:18:20 - error TS2339: Property 'registerPlugins' does not exist on type &apo ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

Avoid risky assigning value of type `any`

Currently, I am incorporating TypeScript into my client-side application. However, upon running the application, I encounter two specific errors: @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an `any` value. @typescript-eslint/no-unsafe-me ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

Stop automatic variable updates in Angular

In Angular, variable x is assigned to variable y. Whenever variable x changes, y also gets changed. How can this behavior be prevented? ngOnInit() { this.editFunction() } editFunction(){ for (let i = 0; i < this.editingData["tags"].length; i ...

Unable to connect a unique FormGroup (using ControlValueAccessor) within a FormArray

We are working with two components, referred to as parent and child, both implementing ControlValueAccessor. The parent form is defined as follows: this.formBuilder.group({ children: this.formBuilder.array([]) }) While the child form looks like this: ...