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

Guide on implementing ng-bootstrap in AngularJS 2 (utilizing angular-cli version 1b15)

I've been attempting to incorporate ng-bootstrap into my Angular 2 project by following the guidelines provided on the official ng-bootstrap website. Here's what I have done so far: npm install <a href="/cdn-cgi/l/email-protection" class="_ ...

Is there a way to use dot notation in TypeScript for a string data type?

I'm currently in the process of developing a function API with a specific format: createRoute('customers.view', { customerId: 1 }); // returns `/customers/1` However, I am facing challenges when it comes to typing the first argument. This ...

Submitting a value to ngForm: A step-by-step guide

I am working on an ngForm within Angular Material that contains several input fields. I want to include a new field called total in the submission, but this field is not an input field. It should be a readonly field and its value needs to come from the Typ ...

Removing items with properties that are null or undefined

My current situation involves using the AWS SDK, and I've noticed that many of its objects have members that can be undefined. Take for example S3.Object: export interface Object { /** * */ Key?: ObjectKey; /** * * ...

Angular 2 - Implementing click event functionality to add an item

I've searched for a solution to this before, but the best answer I could find was from 9 months ago: here and it doesn't work with the latest Angular version. Is there a way to add a new item (<li> or any other) to my HTML with a simple cl ...

Changing a string to HTML within an Angular 2 application

Is there a simple way to convert a string to HTML? I am attempting to convert a string containing valid HTML, href links, and line breaks. Currently, I am utilizing the DOMParser().parseFromString method as outlined on https://developer.mozilla.org/en-US ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Is there a way to carry out tests on keydown events within Jasmine by specifying the keyCode within an Angular2+

I am working on a project where I need to trigger keydown events on an <input> field. Tools Used Karma v1.7.1 as the test runner Tests running on Chrome browser Using Angular 5 framework Any insights on how I can achieve this? ...

Any suggestions for a more effective method of managing authentication in Angular2 rc3 besides using guards?

After upgrading to router 3.0.0-alpha.8, I encountered a hurdle with authentication in my existing Angular2 app. Previously, I handled login/authentication by extending the RouterOutlet with an AuthRouterOutletDirective. This allowed me to easily check if ...

Verify whether the object is properly implementing the interface

Design: export interface Person { id: number; firstName: string; lastName: string; age: number; } Is there a way to verify that an object returned from the backend aligns with the structure defined in the Person interface? ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

The number of columns does not align with the number of values in the first row in Angular 8

Currently, I am in the process of adding a new Vendor to my database by sending a POST request through my Angular App. Here is the code snippet from vendor.service.ts: addVendor(data) { return this.http.post<any>(this.apiUrl + `vendormanagemen ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

Exploring the power of flow.js within an Angular 2 Typescript project

I am trying to incorporate flowjs or ng-flow into my Angular 2 application. After installing the flowjs typings using npm install --save-dev @types/flowjs from However, upon importing it into my component with import { Flow } from 'flowjs';, ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

TypeScript's HashSet Implementation

I'm working on a simple TypeScript task where I need to extract unique strings from a map, as discussed in this post. Here's the code snippet I'm using: let myData = new Array<string>(); for (let myObj of this.getAllData()) { let ...

Set up a TypeScript project with essential dependencies for creating multiple raw JavaScript output files

Currently, I am in the process of developing scripts for Bot Land, a real-time strategy game that offers a unique gameplay experience. Rather than controlling units traditionally with a mouse and keyboard, players code their bots using an API to engage in ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...

How can I properly include DefinitelyTyped TypeScript definition files in a .NET Core project?

Previously, under asp.net for .net framework, I utilized NuGet to incorporate TypeScript type definitions from third-party libraries (*.d.ts files) provided by DefinitelyTyped. However, with the shift to .NET Core, it seems that NuGet is no longer recommen ...

Can you provide details about the launch configuration for pwa-node in VSCode?

When setting up npm debugging in VSCode, I couldn't help but notice that the default launch configuration is labeled as "pwa-node" instead of just "node". Here's what the "Launch via NPM" configuration looks like: And this is what the generated ...