Having trouble with Angular 2 when submitting a form

Whenever I try to submit a form with two input fields and one select list, the submitted value for the select list is always 0. I am unsure where I am making a mistake. When I post this form to an API, all values are correct except for the select list value.

HTML

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="InviteUserForm" (ngSubmit)="Invite(InviteUserForm.value)">

                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-user"></i></span>
                        <input type="text" [(ngModel)]='inviteUser.username'class="form-control" id="username" placeholder="Name" autofocus
                               [ngFormControl]="InviteUserForm.controls['username']"
                               #username="ngForm" />
                    </div>
                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                        <input type="email" [(ngModel)]='inviteUser.email' class="form-control" id="email" placeholder="Email" autofocus
                               [ngFormControl]="InviteUserForm.controls['email']"
                               #email="ngForm" />
                    </div>

                    <div class="input-group margin-bottom-20">
                        <span class="input-group-addon"><i class="fa fa-glass"></i></span>
                        <select [(ngModel)]='inviteUser.partner' class="form-control" [ngFormControl]="InviteUserForm.controls['partner']"
                               #partner="ngForm">
                            <option *ngFor="let p of _partners" [value]="p.Id">{{p.Name}}</option>
                        </select>
                    </div>
                    <button type="button" class="btn-u btn-u-default margin-right-5" data-dismiss="modal">Close</button>
                    <button type="submit" [disabled]="!InviteUserForm.valid" class="btn-u pull-right">Invite</button>
                </form>

Component

import { Component, Inject } from '@angular/core';
import { NgForm }    from '@angular/forms';
import { FORM_PROVIDERS, ControlGroup, FormBuilder, Validators } from '@angular/common';
import {UserService} from '../../services/user.service';
import {OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { Router }  from '@angular/router';
import { HttpHelper} from '../../utils/httphelper.utils';
import 'rxjs/Rx';
import {InviteModel} from '../../models/invite.model';
@Component({
    selector: 'invite-user',
    templateUrl: '../../app/components/user/invite-user.html',
    providers: [UserService, HttpHelper]
})

export class InviteUserComponent {
    InviteUserForm: ControlGroup;
    private _partners: Observable<any[]>;
    private name: string;
    private email: string;
    private partner: number;
    private _data: Observable<any[]>;
    inviteUser: InviteModel;

    constructor(
        @Inject(FormBuilder) public formBuilder: FormBuilder,
        @Inject(UserService) private _userService: UserService) {

        this.inviteUser = new InviteModel();
        this.InviteUserForm = this.formBuilder.group({
            'username': [this.inviteUser.username, Validators.required],
            'email': [this.inviteUser.email, Validators.required],
            'partner': [this.inviteUser.partner, Validators.required]
        });
    }
    ngOnInit() {
        this._userService.partners()
            .subscribe(data => this._partners = data,
            error => {
                console.log("error while retriving partners");
                this._userService.handleError(error);
            }
            );
    }

    Invite(inviteUser) {
        console.log(inviteUser);
        this._userService.inviteUser(inviteUser)
            .subscribe(data => {
                console.log(data);
                this._data = data;
            },
            error => {
                console.log("error while retriving partners");
                this._userService.handleError(error);
            });
    }
}

Model

export class InviteModel {

    public username: string;
    public email: string;
    public partner: number;

}

Image

https://i.sstatic.net/2ownJ.png

Answer №1

It appears that you are employing [value], which represents the value attribute and stores the value as a string. This may lead to issues when assigning the value partner.

I recommend utilizing [ngValue] (to maintain the value's type) rather than [value].

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

Encountering an uncaughtException: Error stating that the module '....nextserverapphomelibworker.js' cannot be located while attempting to utilize pino.transport in Next.js

I recently set up a Next.js project with typescript using create-next-app. Opting for Pino as the logging library, recommended by Next.js, seemed like the logical choice. Initially, when I utilized Pino without incorporating its transport functionality, e ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

Using location.reload with the argument of true is no longer recommended

While it's generally not recommended to reload an Angular Single Page Application, there are situations where a full reload is necessary. I've been informed by TSLint that reloading is deprecated. Is there any other solution available for this ...

Sharing data between two components in an Angular2-Meteor application

I am currently working with angular2-meteor. When attempting to transfer a value between two components (updating the value in the first component triggers an event in the second component where the new value is used), I have two methods available: The ...

Suggestions for the output of an Angular 2 async validator when employing observables

How should the customerNameValidator handle the async validation result for the 'customerName' FormControl invalidation? this.customerForm = this.formBuilder.group({ customerName: [this.newCustomerName, [Validators.minLength(2), Validators.requ ...

The silent renewal feature in oidc-client-js is not functioning properly

I have been utilizing the oidc-client-js library to interact with IdentityServer3, and it functions flawlessly. However, I am encountering an issue trying to set up automatic "silent token renew." Every time oidc-client-js attempts to renew the token, I re ...

Tips for preventing duplicate data fetching in Next.js version 13

I am currently in need of retrieving information from the database, generating metadata, and displaying the page content. The current method I am using is as follows: export const generateMetadata = async ({ params: { questionSlug }, }: Props): Promise&l ...

What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt: <div class="faq-item-container"> <h1 class="mt-1 mb-5"><strong>Frequently A ...

Binding in Angular for internationalization (i18n)

What is the best way to translate a binding using Angular's built-in i18n feature? //translating attribute works fine <mycomponent i18n-myattribute myattribute="just an attribute"></mycomponent> //how to handle translating bi ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Using ngModel in multiple mat-select elements in Angular 2/4

I have a mat-select dropdown list that allows multiple selections and I am using NgModel to keep track of the user's selected values. The issue arises when I navigate away from the page and return, the user's selected values are not preserved in ...

Is it possible for NodeJS to prioritize IPv6 DNS lookups as the default option?

In my work with multiple TypeScript (NodeJS 14) client applications that are all Dockerized, I primarily use axios for most HTTP requests. However, there are other tools used as well. Typically, DNS queries default to resolving IPv4 addresses, resulting i ...

Exploring Angular unit testing for immutable variables

Currently, I am working on writing unit tests for a specific class that contains readonly class variables. I am trying to ensure complete test coverage and understand how to cover the logic inside these variables. import { Injectable } from '@angu ...

Find the calculated values within an Angular Material table

I came across this fantastic example of an Angular Material table with checkboxes that fits perfectly with what I want to implement in my application. However, I am facing a challenge - I need to calculate the total value of the checked rows. Specifically, ...

What is the best way to export an Angular application for users who do not have access to npm

Currently, I am developing an Angular application for a school assignment. The project is complete and runs smoothly on the console. Unfortunately, our instructors lack the patience and IT expertise to install NPM and run the project via the console. Is ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Guide to creating unit tests using Mocha, JsDom, and Angular

I am currently working on setting up a unit test project using Mocha and Angular. In order to execute it in the console with jUnit report for Jenkins, I have included JsDom in my project. However, I am facing an issue with loading my Angular application. ...

Testing the Snackbar function with Angular and TypeScript: Unit Testing

I've encountered an issue with a method called onDelete that utilizes a MatSnackBar which is injected in the constructor like so: constructor(private todoListService: TodolistService, private snackBar: MatSnackBar) { } onDelete(todoList: TodoList): v ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

Applying Multiple Conditions to setCellProps in Material-UI

I am facing an issue with a data-table that is not in a class extending the React.Component, unlike some examples I have come across. My goal is to setCellProps based on certain conditions as outlined below: If utilization is less than or equal to 50, the ...