Issue with Value Update in Angular 7 Reactive Forms

I am encountering an issue where the data in my formgroup does not update upon submission.

The formgroup successfully retrieves values from an API, but when attempting to update and return the value, it remains unchanged. I am unsure of what mistake I may be making.

I am utilizing reactive forms with Angular 7.

modify-view-action.component.html

    <div fxLayout="column" fxLayoutGap="25px" class="modify-view-container">
  <mat-card class="view-settings-descrpition-card">
    <mat-card-content fxLayout="column">

      <form [formGroup]="modifyActionForm">
        <div class="container" fxLayout="row" fxLayoutGap="25px">
          <div class="column1" fxLayout="column">
            <p>Folder: {{dbrAction.FolderTag.Value}}</p>
            <p>Primary Table: {{dbrAction.PrimaryTable}}</p>
            <p>Special Use: {{dbrAction.SpecialUse}}</p>
            <mat-form-field>
              <mat-label>Name</mat-label>
              <input matInput formControlName="ActionName">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Keywords</mat-label>
              <input matInput formControlName="Keywords">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Description</mat-label>
              <input matInput formControlName="Description">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Icon</mat-label>
              <mat-select formControlName="Icon" ngDefaultControl>
                <mat-option formControlName="Icon"
                  ngDefaultControl>
                  {{dbrAction.Icon}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Priority</mat-label>
              <input matInput formControlName="Priority">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Title Font Size</mat-label>
              <mat-select formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                <mat-option formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                  {{dbrAction.TitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Subtitle Font Size</mat-label>
              <mat-select formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                <mat-option formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                  {{dbrAction.SubtitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Title Font Size</mat-label>
              <mat-select formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                <mat-option formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                  {{dbrAction.PrintTitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Subtitle Font Size</mat-label>
              <mat-select formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                <mat-option formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                  {{dbrAction.PrintSubtitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <!-- <mat-form-field>
              <mat-checkbox matInput formControlName="IsActive" [(ngModel)]="dbrAction.IsActive" [value]="dbrAction.IsActive" [labelPosition]="labelPosition">Is Active: </mat-checkbox>
            </mat-form-field> -->
          </div>
        </div>
      </form>

modify-view-action.component.ts

    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'modify-view-action',
  templateUrl: './modify-view-action.component.html',
  styleUrls: ['./modify-view-action.component.scss']
})
export class ModifyViewActionComponent implements OnInit {
  objectData: any;

  constructor(private fb: FormBuilder) { }

  dbrAction: any;
  labelPosition: 'before' | 'after' = 'before';
  modifyActionForm: FormGroup;

  ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: new FormControl(this.dbrAction.FolderTag),
    PrimaryTable: new FormControl(this.dbrAction.PrimaryTable),
    SpecialUse: new FormControl(this.dbrAction.SpecialUse),
    ActionName: new FormControl(this.dbrAction.ActionName),
    Keywords: new FormControl(this.dbrAction.Keywords),
    Description: new FormControl(this.dbrAction.Description),
    Icon: new FormControl(this.dbrAction.Icon),
    Priority: new FormControl(this.dbrAction.Priority),
    TitleFontSize: new FormControl(this.dbrAction.TitleFontSize),
    SubtitleFontSize: new FormControl(this.dbrAction.SubtitleFontSize),
    PrintTitleSize: new FormControl(this.dbrAction.PrintTitleSize),
    PrintSubtitleSize: new FormControl(this.dbrAction.PrintSubtitleSize),
    IsActive: new FormControl(this.dbrAction.IsActive)
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }

  get f() { return this.modifyActionForm.controls; }


initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}

Answer №1

It appears that the formControls you are using have the same names as the dbrAction properties. In this case, you can simplify your code by utilizing FormBuilder: https://angular.io/api/forms/FormBuilder

this.createForm = this.formBuilder.group(this.dbAction);

By doing this, a formGroup will be created with the properties and values of dbrAction (a convenient way to generate a formGroup from an object).

If you choose to manually create the FormGroup (as you have done), you can make use of the patchValue function to assign values to each FormControl:

this.createForm.patchValue({
   Name: this.dbrAction.Name,
   Age: this.dbrAction.Age,
   Gender: this.dbrAction.Gender,
   Email: this.dbrAction.Email
   ....
})

I hope this information proves to be useful for you.

Answer №2

Feel free to give this a try, it may be just what you need.

ngOnInit() {
    this.loadData();
    this.editForm = this.fb.group({
    FolderTag: [this.action.FolderTag],
    PrimaryTable: [this.action.PrimaryTable],
    SpecialUse: [this.action.SpecialUse],
    ActionName:[this.action.ActionName],
    Keywords: [this.action.Keywords],
    Description: [this.action.Description],
    Icon: [this.action.Icon],
    Priority: [this.action.Priority],
    TitleFontSize: [this.action.TitleFontSize],
    SubtitleFontSize: [this.action.SubtitleFontSize],
    PrintTitleSize: [this.action.PrintTitleSize],
    PrintSubtitleSize: [this.action.PrintSubtitleSize],
    IsActive: [this.action.IsActive]
    });

    this.dataObject = this.editForm.value;
    console.log(this.dataObject);
  }

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

Zurb's Vertical Navigation Bar: A Stylish and Functional Design

I attempted to replicate the left navigation bar from this link: The responsive navigation bar and contents on the right caught my attention. Currently, I am working on a project that requires a similar navigation bar. While I am proficient in HTML and C ...

Show a loading image after clicking on an image or button using JavaScript

I recently created an App using PhoneGap and JqueryMobile. Transitioning between multiple HTML pages by clicking on images seems to be causing slow loading times, leaving end users unaware of what's happening in the background. I am looking for a way ...

Add slides in PowerPoint before or after the currently selected slide to enhance your presentation flow

I'm currently working on a function that pulls data from an API to convert PowerPoint presentations into base64 strings. Once I receive the response object, my goal is to seamlessly insert the slides into the existing presentation, exactly after the s ...

Retrieve an array from JSON encoding using AJAX

I have been attempting to retrieve 4 JSON arrays stored in a separate file and include them in my main file using an AJAX request. However, I'm facing difficulties storing these arrays into variables and logging them in the console. Here are the resul ...

Angular2: Continuous User Authentication Guard

I am in the process of developing an application that requires strict authentication for all users. To enforce this, I have created a LoggedInGuard. However, I find myself having to include canActivate: [LoggedInGuard] in every route definition within my ...

Learn how to implement Angular 8 to listen for changes in an observable within an interceptor

Currently, I am in the process of developing an HTTP interceptor that aims to include an 'access level' parameter in the request. The challenge arises when attempting to extract this value from an observable named currentAccessLevel$. Unfortunate ...

Choose a dynamically generated html element without having to click on it

I've been looking for a way to target a dynamically-generated element (specifically a div with the class "date") using jQuery. While I keep finding references to the .on('click') method, it appears that this only selects the div once the pag ...

Angular2/4: Server-generated Alerts and Notifications

I'm in the process of developing a fresh Angular 2/4 application. One of the requirements for the homepage is to display urgent or emergency messages fetched from the server. I've explored several libraries but haven't found a suitable solut ...

Having difficulty deploying a Node.js and Angular app on an Azure Web App via Azure DevOps

I am currently working on setting up a pipeline for my MEAN stack application in Azure DevOps. The frontend is developed using Node.js with Angular, while the backend is built with Node.js and Express. 1) Once I deploy the frontend Node.js project to an A ...

Confirm the data within an HTML table and apply color coding to the cells appropriately

Currently, I have an HTML table used to automatically validate data collected from soil pollutants analyses. Here is a snippet describing the table structure: <table id="table1"> <thead class="fixedHeader"> <tr><input type="submit" ...

Utilize dynamic properties in zod depending on the current state

I have an object that may contain one of two properties depending on a state in react known as state. I am attempting to incorporate this into the Zod schema to generate an error if either property is empty or undefined based on the state. Data.ts const d ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

PHP Pagination Made Easy

Currently, I am developing a website focused on HIV prevention information warehousing. Numerous collaborators will be contributing articles using a tinyMCE GUI. The design team is keen on having control over page lengths. They are interested in implement ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

Dealing with Errors - Utilizing Observable.forkJoin with multiple Observable instances in an Angular2 application

One of my Angular applications has two objects, Observable<Object1[]> and Observable<Object2[]>, that call different APIs in the resolver: resolve(): Observable<[Array<Object1>, Array<Object2>]> { const object1 = this.boo ...

Utilize REST API to submit information into the database during the login process

I'm currently working on an API that needs to verify if a user exists in the database. However, I'm facing challenges in posting data from the input fields to the API for user login functionality. Below is a snippet of the HTML code for the logi ...

Creating a personalized validation function in Angular to validate a form field against another form field

Below is the TypeScript code for the EtcAddAuthorityComponent: export class EtcAddAuthorityComponent implements OnInit { // Code here... } The HTML code for the component is as follows: <h1 mat-dialog-title>Add Authority</h1> <div mat-di ...

Utilizing TypeScript Generics for Creating Arrays of Objects with Inherited Type Definitions

I'm exploring the concept of type inheritance for an array of objects, where one object's value types should inherit from another. While I'm unsure if this is achievable, it's definitely worth a try. Currently, I believe my best approac ...

Having difficulty in replicating and obtaining flash video content from a website through HTML coding

I'm having trouble downloading a flash video, as traditional download software isn't working. I attempted to directly access the video from the html script itself, following this tutorial : https://www.youtube.com/watch?v=waE3J0Jej_0 The script ...