Retrieve the value of an ng-select component upon submitting a form

As a newcomer to Angular, I'm seeking guidance on how to properly handle form submissions with NgSelect in my project.

Within my new-team.component.html file, I have the following code structure:

<app-header></app-header>
<div class="container">
  <div class="row m-5">
    <div class="col">
      <div class="card">
        <div class="card-header">
          New team creation
        </div>
        <div class="card-body">
          <form #formNewTeam="ngForm" (ngSubmit)="onSubmitNewTeam(formNewTeam)">
            <div class="mb-3">
              <label for="teamName" class="form-label">Team Name</label>
              <input type="text" class="form-control" id="teamName" placeholder="Team name" ngModel #teamName="ngModel"
                name="teamName" required minlength="6" pattern="^[a-zA-Z0-9À-ú.-]{6,}">
              <div *ngIf="teamName.errors && formNewTeam.submitted" class="text-danger">
                <div *ngIf="teamName.errors['required']">Team Name is required</div>
                <div *ngIf="teamName.errors['pattern']">
                  Your team name must be at least 6 characters long and without special characters except -
                </div>
              </div>
            </div>
            <div class="mb-3">
              <ng-select [items]="countries" bindLabel="frenchName" bindValue="id" placeholder="Select a country for your team">
                <ng-template ng-label-tmp let-item="item">
                  <b>{{item.frenchName}}</b>
                </ng-template>
                <ng-template ng-option-tmp let-item="item" let-index="index">
                  <img height="18" width="25" [src]="item.logo" />
                  <b style="margin-left: 10px">{{item.frenchName}}</b>
                </ng-template>
              </ng-select>
            </div>
            <button type="submit" class="btn btn-primary">Create</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

Additionally, here is a snippet from my component file:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { NgForm } from "@angular/forms";
import { Subscription } from "rxjs";
import { Country } from 'src/app/_models/country.model';
import { CountryService } from 'src/app/_services/country.service';
import { User } from "../../_models/user.model";
import { AuthService } from "../../_services/auth.service";

// Component definition and implementation

As I perform the console.log(formNewTeam); operation in my TypeScript file, I am only able to access the value of the input field, not the selection made within the <ng-select>. How can I effectively capture and transmit both values (input field value + <ng-select> value) to my backend API?

For context, the Country object comprises the attributes: id, frenchName, and logo.

Ultimately, I aim to receive the form data with the following format, for instance: teamName = "Real Madrid" and countryId = "10"

Your insights in resolving this matter are highly appreciated. Thank you.

Answer №1

It seems like you have forgotten to include the ngModel directive and the name attribute in your <ng-select> element.

<ng-select
  [items]="countries"
  bindLabel="frenchName"
  bindValue="id"
  placeholder="Select a country for your team"
  ngModel
  name="countryId"
>
    ...
</ng-select>

If you want to display the value of formNewTeam, you can use the following code:

console.log(formNewTeam.value);

Check out the Demo on StackBlitz

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

Angular2 is throwing an error stating that the property 'map' is not found on the type 'Observable'

Here are the imports: import { Component,OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { Application } from './Application'; import { Http, Response } ...

Running "npm start" does not automatically recompile or display code changes

My experience with my Angular project has been smooth until today. Surprisingly, without making any changes, the "npm start" command suddenly stopped working properly. The project compiles successfully, but any subsequent code changes do not trigger an aut ...

Error encountered with object.map() function - what fundamental concept am I missing?

Could someone lend me a fresh set of eyes on this... The React Component is fetching data from MariaDB using a useEffect() hook. The data is retrieved successfully without any errors, and the console.log shows the correct data (refer to the image below). ...

What methods are available to expedite webpack compilation (or decouple it from server restart)?

My current setup includes the following configurations: import path from 'path' import type {Configuration} from 'webpack' const config: Configuration = { mode: 'development', entry: path.join(__dirname, '../..&apos ...

What could be causing my Angular 7 header to be unresponsive?

I am facing issues with my http, header, and RequestOption in the API. I am working with Angular 7.1 and have tried various methods to resolve the problem without success. The error message I am receiving is: The token is not being passed in the header ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Dealing with ViewChild and Stepper ExpressionChangedAfterItHasBeenCheckedError in Angular 8

I am currently facing an issue while using ViewChild to access a child component's attribute in the Stepper [completed] property. The problem is related to the "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. ...

Typescript's Confusion with Array Types: Understanding Conditional Types

Here is the setup I have. The concept is to receive a generic and options shape, deduce the necessary options based on the generic and the type key of the options shape, and appropriately restrict the options. type OptionProp<T extends string | boolean& ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...

I am looking for unique values from a duplicate string that is separated by commas in TypeScript

Using TypeScript, I am trying to extract unique values from a list of comma-separated duplicate strings: this.Proid = this.ProductIdList.map(function (e) { return e.ProductId;}).join(','); this.Proid = "2,5,2,3,3"; The desired output is: this. ...

Using Typescript to implement an onclick function in a React JS component

In my React JS application, I am using the following code: <button onClick={tes} type="button">click</button> This is the tes function that I'm utilizing: const tes = (id: string) => { console.log(id) } When hovering ov ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Storing entire page data to CookieService in angular2: A comprehensive guide

I am currently utilizing angular2 and working on a page that displays a list of items. When a user clicks on an item, its details are shown on a second screen. However, when I refresh the page while on the second screen, all the data is lost. To prevent t ...

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

Accessing Child Properties in Parent Component using Typescript

New to the world of Typescript! Imagine having a component called TitleSubtitle that consists of both a Title and a Subtitle component. The Title component comes with props: interface TitleProps { text: string; } The Subtitle component also has props ...

Angular Material select all checkboxes provide a convenient way to select multiple

Need help with implementing a select all checkbox on Angular Material. The goal is to have the master checkbox show Indeterminate when a specific item is clicked, and then turn to checked once all checkboxes are selected. Currently experiencing some unexpe ...

React typescript is handling various promise response types, causing strange behavior in type-checking

I recently started utilizing the and I seem to be encountering a perplexing issue. If further context is needed, please let me know and I will provide it. All the necessary functions and types are mentioned below my explanatory paragraphs. Your assistance ...