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

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

Using Rails 5 API to generate a new object using JSON with nested resources

Here is the JSON data that was received as parameters from an external Angular web app: { "provincia": { "id": 1, "name": "Province" }, "username": "tester", "direccion": "new avenue 100", "email": "<a href="/cdn-cgi/l/email-protectio ...

When using the ngFor directive, the select tag with ngModel does not correctly select options based on the specified

Issue with select dropdown not pre-selecting values in ngFor based on ngModel. Take a look at the relevant component and html code: testArr = [ { id : '1', value: 'one' }, { id : '2', ...

What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon amon ...

Utilizing SystemJS to Retrieve Files from Subfolders

Having an issue loading my custom angular2 component, Test.component. When using Systemjs, I've set the default extension to .js for everything under /app. However, for some reason it's not appending ".js" to test.component when searching for it ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Is there a way to use an Angular interceptor to intercept and modify static files like .html files? I would like to change the lang

While researching Angular intercepting, I stumbled upon this helpful documentation: here. My goal is to intercept HTML using an Angular interceptor in order to modify the HTML file before it's displayed in the browser. Trying to accomplish this on the ...

How to incorporate a popup modal in your project and where should you place the DialogService constructor

Currently, I am in the process of developing a CRUD ASP.NET Core application using Angular 2 and Typescript. Prior to incorporating a popup feature, this was my output: https://i.stack.imgur.com/vHvCC.png My current task involves placing the "Insert or e ...

Utilize Angular roles to sort and organize website data

Exploring the utilization of login roles in my Angular SPA application which operates solely on the client side, integrated with Spring Security and Spring Boot. I have concerns about potential unauthorized access by a skilled developer who could manipula ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

Encountering an issue that states that jQuery must be included before Bootstrap's JavaScript is causing an

I encountered the following exception: bootstrap.js:240 Uncaught TypeError: Bootstrap's JavaScript requires jQuery. Make sure to include jQuery before Bootstrap's JavaScript at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 a ...

Issue with Angular UI Bootstrap accordion heading behavior when used in conjunction with a checkbox is causing

I have implemented a checkbox in the header of an accordion control using Bootstrap. However, I am facing an issue where the model only updates the first time the checkbox is clicked. Below is the HTML code for the accordion: <accordion ng-repeat="tim ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

What are the ideal scenarios for implementing routing in Angular?

As I embarked on developing my inaugural Angular app, I initially implemented routing with unique URLs for each "main" component. However, upon encountering Angular Material and its appealing tab functionality, I was captivated. What are the advantages an ...

Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance! I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a ba ...

Having difficulty initializing a constant object in TypeScript

Encountering an error while attempting to compile my code using Angular 7.2.0 and TypeScript version 3.2.2: Error TS1005: ',' expected.**… The issue seems to be arising from the line where I am trying to define a const object. addAppareil( ...