Issue with Angular MatSelect Losing Selected Value in Reactive Form Upon Submission

Working on an Angular project with a reactive form that features a <mat-select> for selecting cities. Although the dropdown functions properly in displaying and allowing city selection, there's a problem when attempting to submit the form: the selected value for ciudad_id doesn't seem to be saved or captured correctly in the form object upon submission.

HTML:

<div class="form-group has-default">
  <mat-form-field class="input-group full-width">
    <mat-icon matPrefix>location_city</mat-icon> 
    <mat-select matInput placeholder="City" formControlName="ciudad_id">
      <mat-option *ngFor="let city of cities" [value]="city.id">{{city.name}}</mat-option>
    </mat-select>
    <mat-error *ngIf="ciudad_id?.invalid && ciudad_id?.dirty">
      The city is required.
    </mat-error>
  </mat-form-field>
</div>

Within the component, I set up the form and load the cities successfully. However, when the form is submitted, it appears that the value of ciudad_id is either missing or not accurately captured:

TS:

export class RegisterComponent implements OnInit{
  form!: FormGroup;
  cities = [];

  constructor(private _form_builder: FormBuilder) { }

  ngOnInit() {
    this.initializeForm();
    this.loadCities();
  }

  private initializeForm() {
    this.form = this._form_builder.group({
      city_id: ['', Validators.required],
      // other form controls...
    });
  }

  loadCities() {
    // Cities are loaded from a service and assigned to `cities`
  }

  onSubmit() {
    console.log("Form submitted:", this.form.value);
    // Issue persists where `city_id` does not store the selected value
  }
}

I have attempted subscribing to value changes using valueChanges, and verified that the value does change correctly when selecting a different option. Additionally, I've double-checked the form's binding and ruled out any typos or configuration errors. Despite these efforts, the issue remains unresolved.

Has anyone encountered a similar challenge or can shed light on why the chosen value for city_id isn't retained during form submission?

Answer №1

Have you considered adding the id and name attributes to see if it resolves the issue? If not, try reproducing the problem on a stackblitz and then update your question with the latest details!

....
 <mat-form-field class="input-group full-width">
    <mat-icon matPrefix>location_city</mat-icon> 
    <mat-select matInput placeholder="City" formControlName="city_id"
          id="city_id" name="city_id"> <!-- make sure these are added -->
      <mat-option *ngFor="let city of cities" [value]="city.id">{{city.name}}</mat-option>
          ....

Answer №2

One potential solution is to troubleshoot the ciudad.id value.

<mat-option *ngFor="let ciudad of ciudades" [value]="ciudad.id">The id: {{ciudad.id}}</mat-option>

Another suggestion is to display the current value somewhere on the page:

<div>
    {{ form.value | json }}
</div>

It's worth considering if there is a missing formGroup. Perhaps it needs to be added?

<div [formGroup]="form">
    ...
</div>

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

Evaluating h1 content in HTML using Angular Protactor testing

I am completely new to end-to-end testing. I have a login page in my application that should be displayed to users when they log out. However, I am facing an issue with retrieving the text from a specific div element containing an h1 tag, leading to unexpe ...

Incorporating a picture backdrop into a button element in a React Typescript component

I am working on a React project with TypeScript and using a Material UI library. I am trying to set a background image for a button, but when I use src or imageURL, it gives me a TypeScript error. The CSS style also does not show the picture. Here is my ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Nested Observables in Angular are essential for handling asynchronous

In my service, I have a function that returns an observable array of entity ids. Another function in the service takes an entity id as a parameter and returns detailed information about that entity as an observable. My goal is to retrieve all entity ids u ...

Navigating in Angular 4 using the `router.navigate`

After implementing a login feature in my application's LoginComponent, I encountered an issue. Within the LoginComponent.ts file: onSubmit(loginForm: NgForm): void { if(loginForm.valid) { this.authService.login(loginForm.value) ...

Efficiently setting HttpParams like HttpHeaders in Angular: A streamlined approach

Having recently made the switch from using the old Http API to the new HttpClient API in Angular, I found myself needing to work with HttpHeaders and HttpParams. So far, everything is going smoothly. However, the examples I came across for declarations see ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

Gathering the output from every function within an array of functions

I've searched extensively for a solution to this dilemma, but have had no luck so far. Therefore, I am turning to the community for help. Please feel free to direct me to any existing similar queries. My challenge involves working with an array of fu ...

Tips for styling your Angular Material Card on mobile devices

Currently, I am very happy with my desktop layout which looks like this: https://i.stack.imgur.com/tG0pw.png However, when it comes to the mobile version of my site, here is what I have so far: https://i.stack.imgur.com/KD1hh.jpg While I do like the ho ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

How can I transform a Firestore collection into an array?

I'm struggling with converting the data retrieved from Firestore into an array that can be used for a chart.js graph. Retrieving Data from Firestore fetchData(){ //Get data this.updatesCollection = this.afs.collection(pathStats); this. ...

Is time-based revalidation in NextJS factored into Vercel's build execution time?

Currently overseeing the staging environment of a substantial project comprising over 50 dynamic pages. These pages undergo time-based revalidation every 5 minutes on Vercel's complimentary tier. In addition, I am tasked with importing data for numer ...

Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface. The API is returning a list of objects with various properties, but I only require a few specific properties from the response object. Example of API Response: ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Mapping JSON objects to TypeScript Class Objects

I am in the process of transitioning my AngularJS application to Angular 6, and I'm encountering difficulties converting a JSON object into a TypeScript object list. In my Angular 6 application, I utilize this.http.get(Url) to retrieve data from an AP ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Exploring the depths: Retrieving nested object attributes using ngFor

Trying to display the "type" value in the ngFor table resulted in receiving object '[object Object]' of type 'object.' NgFor only supports binding to Iterables such as Arrays. json [{ "id": 123, "name": "Paul", "cars": { ...