My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it ends up resetting the entire user.

Here is my Form:

<form [formGroup]="persoForm" (ngSubmit)="onSubmit()">
            
                <div id="firma">
                    <mat-form-field appearance="standard" id="firm" floatLabel="always">
                        <mat-label> Firmenbez.:</mat-label>
                        <input matInput type="text" name="firm" formControlName="firmenBez" [value]="person.firmenbezeichnung"/>
                    </mat-form-field>
                </div>
            </form> 

TS

persoForm = new FormGroup({
                firmenBez: new FormControl(),
            })

Checking for null values:

onSubmit() { //currently only there to check if the values are still null
                
                console.log(this.persoForm.getRawValue());
            }

Answer №1

Your input should be sourced from one place, but it seems you are pulling data from two sources in your code: formControlName and value.

When working with Angular Reactive Form, it's important to keep the formControlName separate from the value, and adjust the value based on your API data:

  • If you receive the data before initializing the FormGroup, set it up like this:
// Initialize the form-group when receiving data from the API:
this.personForm = new FormGroup({
  firmenBez: new FormControl(this.person.firmenbezeichnung),
});
  • If you get the data after initializing the FormGroup, stick with your initial setup and patch the data from the API as follows:
onDataReceived(person) {
  this.personForm.patchValue({
    firmenBez: person.firmenbezeichnung,
  });
}

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

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

Obtain numerous variables from a .ts file and bring them into a separate file within Angular 4

I am interested in creating a config.ts file to store the global values of my app. I have been able to use it in this way: module.exports.key = "My key"; However, I need to export multiple values, around 20-30. Is there a more efficient way to do this wi ...

Using Angular to link Google Places API responses to a form: a guide on merging two different length objects with a shared key

I'm struggling with a key concept here regarding displaying the results of a places autocomplete query. I want to replace the types[0] name with more familiar terms such as suburb or city instead of sublocality_level_1 or administrative_area_level_1 ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

Experiencing an issue with type error when transitioning syntax from using require to import

After transitioning from require in CommonJS syntax to import in ES Module syntax, I encountered an error. I decided to develop a todo-app using Node.js, TypeScript, and MySQL. To start off, I wrote the initial code snippets below: // db.ts export {}; co ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

The Angular2 application was constructed using angular-cli, incorporating a directive, and optimized with the ng build

I am working on an angular-cli app and my environment details are: npm -v 3.10.8 node -v v6.9.1 angular2 ^2.4.0 angular/cli 1.0.0-beta.32.3 Recently, I added the following line to my package.json: "angular2-auto-scroll": "1.0.12" You can find more info ...

Sharing data between components in Angular 4: How to pass variables and form content to

Perhaps my wording is incorrect. I am filling out a Client Form with the data from an API response within the NgOnInit function. ngOnInit() { this.indexForm = new FormGroup({ name: new FormControl(Validators.required), status: new FormCo ...

Leveraging Angular's HTTPClients: merging multiple HTTP requests with Observables to optimize asynchronous operations

In my HTML code, I have the following: <ng-container *ngIf="lstSearchResults|async as resultList; else searching"> ... <cdk-virtual-scroll-viewport class="scroll-container"> <div *cdkVirtualFor="let search of resultList" class="card ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

The manager encountered an issue while querying for "Photo" data: EntityMetadataNotFoundError - no metadata could be found

I encountered an error while attempting to utilize typeorm on express: if (!metadata) throw new EntityMetadataNotFoundError(target) ^ EntityMetadataNotFoundError: Unable to locate metadata for "Photo". Below is my data source: import " ...

Tips for monitoring and automatically reloading ts-node when there are changes in TypeScript files

I'm experimenting with setting up a development server for my TypeScript and Angular application without having to transpile the .ts files every time. After some research, I discovered that I am able to run .ts files using ts-node, but I also want th ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

The use of `super` in Typescript is not returning the expected value

Trying to retrieve the name from the extended class is causing an error: Property 'name' does not exist on type 'Employee'. class Person { #name:string; getName(){ return this.#name; } constructor(name:string){ ...

Tips for testing two conditions in Angular ngIf

I am facing a little issue trying to make this *ngIf statement work as expected. My goal is to display the div only if it is empty and the user viewing it is the owner. If the user is a guest and the div is empty, then it should not be shown. Here is my cu ...

What are some ways to prevent unnecessary HTML re-rendering when using this.sanitizer.bypassSecurityTrustHtml(value)?

What is the best way to prevent constant HTML re-rendering when utilizing (this.sanitizer.bypassSecurityTrustHtml(value)) in Angular versions 5 and above? ...