Issue with Angular forms: The value of the first input element does not match the value set

I am still learning Angular, so please forgive me if my question seems a bit basic.

Currently, I have a reactive form that retrieves data for editing from my controller. It seems to be working but there are some bugs present.

Controller:

  myForm:any;
            expense:any;

            constructor(private fb:FormBuilder, private exService: ExpenselistService, private route:ActivatedRoute) {
              this.route.queryParams.subscribe(res => {
                this.exService.load('expdata', res['token']).subscribe(data => {
                  this.expense = data;
                  this.myForm = this.fb.group({
                    extitle:  [this.expense.title, [Validators.required]],
                    examount: [this.expense.amount, [Validators.required, Validators.min(1)]],
                    extype:   [this.expense.type, [Validators.required]]
                  });
                });
              });
            }
          

View:

  <form [formGroup]="myForm" (ngSubmit)="doSubmit()">
        <div class="form-floating mb-2">
          <input type="text" id="title" class="form-control" formControlName="extitle" placeholder="Title">
          <label for="title">Title</label>
        </div>
        <div class="form-floating mb-2">
          <input type="number" id="amount" class="form-control" formControlName="examount" placeholder="Amount">
          <label for="amount">Amount</label>
        </div>
        <div class="mb-2 text-center">
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" checked formControlName="extype" id="exdebit" value="debit">
            <label class="form-check-label" for="exdebit">Debit</label>
          </div>
          <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" formControlName="extype" id="excredit" value="credit">
            <label class="form-check-label" for="excredit">Credit</label>
          </div>
        </div>
        <div>
          <button type="submit" class="btn btn-success py-2 px-3 rounded-5">Save</button>
        </div>
      </form>
    

The problem is that the title does not get updated with the value from the controller when an edit is being made. It remains empty, while the amount and type fields function correctly. Strangely, when I console.log the data, it shows the correct values including the title. Even after duplicating the title element without any changes, the duplicate shows the value but the original input field at the top stays empty.

Any assistance on this issue would be highly appreciated.

Answer №1

Revise your code in this manner:

  myForm: FormGroup = this.fb.group({
          extitle:  ['', [Validators.required]],
          examount: ['', [Validators.required, Validators.min(1)]],
          extype:   ['', [Validators.required]]
        });

  constructor(private fb:FormBuilder, private exService: ExpenselistService, private route:ActivatedRoute) {
    this.route.queryParams.subscribe(res => {
      this.exService.fetchData('expdata', res['token']).subscribe(data => {
        this.myForm.patchValue({extitle: data.title, examount: data.amount,extype: data.type})
      });
    });
  }

The form should be initialized once and then use patchValue for subsequent modifications.

Retrieve data by accessing the form like this: this.myForm.getRawValue()

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

The flag will never turn true; it's stuck in the false position

Currently, I am in the process of developing a custom hook to store data on a server. To mimic the server call, I have implemented a simple setTimeout function that changes the value of the data creation flag to true after 2 seconds. I have a specific fun ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

What is the best way to remove all validators from a different component in Angular 7 using reactive forms?

I need to find a way to clear all validation in a form group on a sibling component when a boolean value is selected on another component within the same application. Is there a solution for achieving this? We have implemented a method in our application ...

What is the best way to define the typings path for tsify?

My TypeScript sources are located in the directory: src/game/ts The configuration file tsconfig.json can be found at: src/game/ts/tsconfig.json Additionally, the typings are stored in: src/game/ts/typings When running tsc with the command: tsc --p s ...

Best Practices for Showing JSON Data from MongoDB in an Angular Material Table

Desire I'm trying to extract data from MongoDB and exhibit it in an Angular Material Table. Problem Even though I can view the results of my MongoDB query in the console/terminal, the Chrome browser console indicates that my JSON data has been save ...

Is there a way to extract the current view date information from fullcalendar using Angular?

When working with HTML code... <full-calendar defaultView="dayGridMonth" [plugins]="calendarPlugins" #calendar></fullcalendar> I am wondering how to extract the date information from the #calendar element. I attempted to consult the fullcal ...

Unexpected termination during the npm installation process without providing a clear error message

Every time I try to create a new Angular2 app using the command ng new new-app, angular-cli successfully generates the necessary files and then proceeds to run npm install. However, the npm install process abruptly stops with no error message provided. As ...

Prod build of an Ionic 5 and Angular 9 application fails to load, although it functions correctly when using Ionic serve. Surprisingly, no errors are displayed

After migrating my app from ionic 4 to 5 and Angular 7 to 9, I implemented all necessary changes in configuration and code to ensure a smooth transition. The Ionic serve command works perfectly and there are no errors when creating a production build. Howe ...

Using a Component as a Property in Angular

There is a small gridComponent: @Component({ selector: 'moving-grid', templateUrl: './grid.component.html', styleUrls: ['./grid.component.css'] }) export class GridComponent { @Input('widgets') ext ...

Is there a TypeScript equivalent to NSUserDefaults or SharedPreferences?

Just getting started with Angularjs-2.3 TypeScript and I have a specific scenario where I need to save the userId in the app so it can be accessed anywhere within the app. If I were developing for Android or iOS, I would typically use NSUserDefaults and S ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

What is the best way to display two arrays next to each other in an Angular template?

bolded text I am struggling to display two arrays side by side in an angular template. I attempted to use ngFor inside a div and span but the result was not as expected. A=[1,2,3,4] B=[A,B,C,D] Current Outcome using ngFor with div and span : Using Div : ...

An issue arises in React TypeScript where a callback function is encountering undefined values when using setState, but surprisingly logs the

Struggling with a React application I'm building, specifically with an issue that's got me stumped. Here's a snippet of code that's causing trouble: onFirstNameChange(event: any){ console.log(event.target.value) // this.setState ...

Guide to implementing a specified directive value across various tags in Angular Material

As I delve into learning Angular and Material, I have come across a challenge in my project. I noticed that I need to create forms with a consistent appearance. Take for example the registration form's template snippet below: <mat-card> <h2 ...

Steps to utilize the POST method with Angular, NodeJs/ExpressJs, and MySQL:

I am facing an issue with my Angular project where the GET method works fine, but when I try to call the POST method it seems like the POST function in Node.js is not getting called. Can someone help me figure out what I am doing wrong? Below are the snip ...

Differences between Typescript static methods and functions defined outside of classesWhen comparing Types

What distinguishes a static class method from a function defined outside a class in TypeScript, especially when visibility is not a concern? While there are differences in visibility from other classes and files, what factors should be considered when dec ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: https://i.sstatic.net/jZ6kk.png Below are ...

What is the best way to implement the usehook function in a function using react and typescript?

When attempting to utilize the useHook in a function, an error message appears stating that useHook is being used within a function which is neither a React function component nor a custom React hook. I encountered an error when trying to use the useOpen ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...