Do we need to manually transfer data between component data and form data when saving/loading from a web API?

When I submit data in my reactive form, the stored object is returned from the server. This can happen due to server logic altering a field that needs to be updated on the client side as well.

onSave() {
  const data = this.form.value;
  console.log("saving", data);

  this.service.save(data)
    .subscribe(
      suc => {
        this.data = suc;
        console.log("saving succeeded", suc);
      },
      err => console.log("saving failed", err)
    );
}

I've noticed that changes in the data model don't affect the controls on my page. As a workaround, I reset the form value explicitly using this.form.setValue(this.data) as outlined below.

onSave() {
  const data = this.form.value; ...
  this.service.save(data)
    .subscribe(
      suc => {
        this.data = suc;
        this.form.setValue(this.data);
      }, ...
    );
}

While this approach achieves the desired outcome, it feels somewhat unconventional. I have a nagging feeling that I'm masking a design flaw rather than addressing it directly. Perhaps there should be an automatic linkage between component and form data. Currently, I manually copy data from the form to the component before saving, and vice versa after saving. Given that this process is repeated for every operation, I believe there should be a more streamlined solution available.

Am I handling this situation correctly, or is there a step I overlooked?

Answer №1

Have you ever experimented with the patchValue method in Angular?

onSave() {
  const formData = this.form.value; ...
  this.service.save(formData)
    .subscribe(
      success => {
        this.form.patchValue(success);
      }, ...
    );
}

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

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

Utilize ngrx/store to capture events from various components within an Angular application

Is there a way to utilize ngrx store in Angular to capture events from a grandchild component without relying on a service, Behavior Subject, or @Output? ...

How to temporarily modify/add CSS class in Angular 2

In my Angular 2 application, there is a label that displays the current amount of points for the user. Whenever the number of points changes, I want to briefly change the class of the label to create an animation effect that notifies the user of the chang ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

What steps should I take to fix this TypeScript error?

I've been struggling to fix this error, but I'm unsure of the best way to resolve it. Here is the code snippet I've been working with:https://i.sstatic.net/m6M48.png Here is the specific error message: https://i.sstatic.net/uk6QY.png ...

Error: script took too long to execute, no response received within 11 seconds

During my integration test, I encountered an error message saying Failed: script timeout: result was not received in 11 seconds To investigate further, I navigated to the Chrome browser performance tab and noticed several yellow indicators showing scripti ...

Angular 8: When deployed on Heroku, subscribing to an observable yields HTML instead of JSON, however, this issue does not occur when

Issue Synopsis Encountering an error message stating Unexpected token < in JSON at position 0 at JSON.parse while attempting to fetch data from MongoDB. The code functions correctly in Angular 7, and when running locally in Angular 8, but fails when de ...

Angular 2 client for Spring Boot Birt Report produces faulty PDF documents

I am currently setting up a BIRT report within a Spring Boot application that is being accessed by an Angular 2 client. Below is the code snippet where the report is executed: @PostConstruct public void startUp() { if(inputDir == null) throw n ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

The class is not correctly implementing the 'OnInit' interface. The 'ngOnInit' property is missing in the 'Component' type, which is required in the 'OnInit' type

Could someone offer assistance with this issue? It seems like there are errors in the code structure: Class 'ContactFormComponent' incorrectly implements interface 'OnInit'. Property 'ngOnInit' is missing in type 'Contac ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...

Unable to display information stored in the Firebase database

I am struggling with a frustrating issue. My goal is to showcase the information stored in the Firebase database in a clear and organized manner, but I'm having trouble achieving this because it's being treated as an object. getData(){ firebas ...

Troubleshooting Next.js 14 JWT Session Error in Conjunction with Next Auth - addressing a type

Recently, I delved into working with Next.js 14 and Next Auth 5 beta. However, every time I attempt to log in, I encounter the following error: [auth][error][JWTSessionError] [auth][cause]: TypeError: Cannot read properties of undefined (reading 'user ...

Prevent Click Event on Angular Mat-Button

One of the challenges I'm facing involves a column with buttons within a mat-table. These buttons need to be enabled or disabled based on a value, which is working as intended. However, a new issue arises when a user clicks on a disabled button, resul ...

Angular application unable to invoke the Web API GET method

Just starting out with Angular. I've got a WebAPI controller set up with a get method that returns data. Everything runs smoothly when I access it from the browser directly. But for some reason, when I try to call the same method from my Angular ap ...

Ways to incorporate only essential UI elements in @angular/material

In the process of creating my Angular application, I am looking to streamline its size. Currently, my app relies on Angular Material, but upon inspecting the node_modules folder, I realized that there are unused UI components such as autocomplete and check ...

What is the best way to assign ngModel to dynamically inserted input rows in Angular 4+ (specifically in a mat-table)?

Just a quick question - how can I add ngModel to dynamically added new input rows? I have a Mat table with multiple rows and an "add element" method that adds a new row every time a button is clicked. This way, I want to bind the user-entered values and se ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

The Angular Material side navigation module is not being acknowledged

Currently, I am utilizing Angular version 9.1.11 in conjunction with Angular Material version 9.2.4. The issue arises when attempting to import the MaterialSidenavModule, which is required for utilizing components like mat-sidenav-container. Below is a sn ...

How to Manage API Requests in React Native?

I am in the process of familiarizing myself with react native and attempting to communicate with an API helper that I have implemented within one of my screen files. While I suspect there may be a syntax error causing issues, I also wonder about the overal ...