angulartypescriptangular-formsangular-ngselectangular16

Get value of ng-select on form submit


I'm quite new to Angular.

I have this HTML file new-team.component.html:

<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>

and this is 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({
  selector: 'app-new-team',
  templateUrl: './new-team.component.html',
  styleUrls: ['./new-team.component.scss']
})
export class NewTeamComponent implements OnInit, OnDestroy {
  user!: User;
  countries: Country[] = [];
  AuthUserSub!: Subscription;

  constructor(
    private authService: AuthService,
    private countryService: CountryService
  ) {
  }
  ngOnInit(): void {

    this.AuthUserSub = this.authService.AuthenticatedUser$.subscribe({
      next: user => {
        if (user) this.user = user;
      }
    })

    this.countryService.getAllCountries().subscribe({
      next: data => {
        this.countries = data;
        this.countries.forEach(element => {
          element.logo = "/assets/flags/" + element.logo;
        });
      },
      error: err => console.log(err)
    })
  }

  onSubmitNewTeam(formNewTeam: NgForm) {
    console.log(formNewTeam);
    if (!formNewTeam.valid) {
      return;
    }
  }

  ngOnDestroy() {
    this.AuthUserSub.unsubscribe();
  }
}

On the line where I call the console.log(formNewTeam); on my .ts file I just have the value of the input field, not the value selected into the <ng-select>. How can I send these two values (input field + value of the <ng-select>) to my backend API?

By the way, the Country object contains id, frenchName, and logo.

I should receive the form with these two values for example: teamName = "Real Madrid" and countryId = "10"

Thank you in advance.


Solution

  • You are missing the ngModel directive and name attributes 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>
    

    To print the formNewTeam value, you should use:

    console.log(formNewTeam.value);
    

    Demo @ StackBlitz