Updating reactive form fields with setValue or patchValue does not result in the fields being refreshed

This is a simplified version of my code snippet:

ngOnInit() {
    //initialize form fields 
    this.form = this.builder.group({
      name: '',
      age: '',
      location: '',
    });

    //Calling the service

    this.dataService.getDetails().subscribe(
      (data) => {
        this.dataArray = data;
        if (this.dataArray[this.count].status === 'OK') {
          let docs = {};
          this.someService.getDocs(this.dataArray[this.count].id).subscribe(
            (data) => {
              docs = data;
              console.log("docs: ", docs);
              this.setFormValues(docs);//setting form values
            },
            (err) => {
              console.log(err);
              console.log('An error occurred');
            }
          );
        }
      },
      (err) => {
        console.log(err);
        console.log('Something went wrong',err);
      }
    );
  }

After successfully printing the field values in the setFormValues() function, I encountered an issue when I attempted to bind these values to the form using setValue or patchValue. The form did not update with the fetched values from the service.

Additional code related to this issue:

public setFormValues(doc: DocsDTO) {
    if (doc!= null) {
      console.log("setFormValues", doc);
      this.form.patchValue({
        name: doc.name == null ? '' : doc.name.text,
        age: doc.age == null ? '' : doc.age.text,
        location: doc.location == null ? '' : doc.location.text,
      })
    }
  }

This is the structure of my form:

<form [formGroup]="form">
          <mat-card-content>
            <input placeholder="name" [formControl]="name" id="name"
              ngDefaultControl></input>
            <input placeholder="age" [formControl]="age" id="age" ngDefaultControl></input>
          </mat-card-content>
        </mat-card>
</form>

Please note: When I do not use FormBuilder and initialize form fields with FormControl, and set form values with this.name.setValue(), the process works correctly.

Being new to Angular, I am unsure of what mistake I am making in this scenario.

Answer №1

Everything seems good to me except for the part where you are defining the pathvalue:

The doc.name.text doesn't seem accurate to me. You might want to try

this.form.patchValue({
    name: !!doc.name ? doc.name : '',
    age: !!doc.age ? doc.age: '',
    location: !!doc.location ? doc.location : '',
  })

This will update our FormControl instances in a straightforward manner! Additionally, I believe that the conditional setting is unnecessary here because:

setting pathvalue does not cause any errors due to the if check within the Object.keys loop. Some may argue that it’s a safe $apply, but I'm joking. It allows you to assign values to existing properties and ignores those that do not currently exist in the control being iterated over

On the contrary, setValue is considered a "safer" approach. It will throw an error for properties that do not exist.

If you properly add the formControlName, it should work correctly:

 <input placeholder="name" formControlName="name" id="name" ngDefaultControl>
 <input placeholder="age" formControlName="age" id="age" ngDefaultControl>

Check out the stackBlitz demo I created for you here:

Answer №2

One issue is present in your HTML code where the input is using "formControl", therefore, the proper way to bind formGroup with form in this scenario is to utilize the [formControlName] directive.

To resolve this, modify your HTML as follows:

<form [formGroup]="form">
          <mat-card-content>
            <input placeholder="name" [formControlName]="'name'" id="name"
              ngDefaultControl></input>
            <input placeholder="age" [formControlName]="'age'" id="age" ngDefaultControl></input>
          </mat-card-content>
        </mat-card>
</form>

By making this change, everything will work correctly.

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

Organizing a collection of bags using ng2-dragula technology

I have successfully implemented ng2-dragula for a dynamic sorting user interface. Currently, I can reorder the <li> elements within each container. <div *ngFor="let bag of chest" class='container'> <ul [dragula]='"bag-one"& ...

An issue has occurred: it seems that the property cannot be accessed because `this.child` is undefined

Is there a way to call the function "initMap" that is defined in the child component "UpdatePinComponent", from the parent component named "ApiaryComponent"? Below is a snippet of the TypeScript code from the parent component: import { AfterViewInit, Compo ...

Angular: a versatile button that can perform various actions

My item has the capability to undergo various actions such as edit, delete, copy, upgrade, and more. Depending on the status of the item, only one action can be executed at a time. Therefore, I aim to develop a button component in Angular that will be dis ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...

Can we determine the data type of a value within a class instance by utilizing a function to retrieve it?

Is it feasible to create a function that maintains typing and functions in the same way as this: class Example { someNumber:number = 1; someString:string = "test"; } const example = new Example(); const value = example.someNumber; // typ ...

Transferring the web application context to an Angular2 service

In my project, I am attempting to pass a variable named _contextPath from a Javascript evaluated variable in a JSP file located in the folder structure shown below. The goal is to make this _contextPath variable available in a Typescript Service called job ...

Get updates on a new subscription for Angular by signing up now

I have a method for authentication that is kept private. Additionally, I have a public method named login which is utilized in my components to carry out the actual login process. I am interested in subscribing to the login method, which internally subscri ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

What is the best way to reference a component variable property within its template without explicitly stating the variable name?

Suppose my component is managing an instance of the following class: class Person { firstName: string; lastName: string; age: number; } Is there a way to directly reference its properties in the template like this: <p>{{firstName}}</p> & ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Customize the color of a specific day in the MUI DatePicker

Has anyone successfully added events to the MUI DatePicker? Or does anyone know how to change the background color of a selected day, maybe even add a birthday event to the selected day? https://i.stack.imgur.com/or5mhm.png https://i.stack.imgur.com/so6Bu ...

Troubleshooting the challenge of transitioning from Angular 4 to Angular 9 with flatMap

In my Angular 4 code, everything runs smoothly: public resolve(): Observable<GridViewDtcConfig> { const permissionResponse = this.flowsService.getPermissions(); return permissionResponse.flatMap((permissions) => { c ...

Is it possible to dynamically assign and call functions through an Object in Angular 6?

I implemented a click handler for a button that is generated dynamically. Within the click handler function, I am invoking a callback function. However, I encountered an issue where an error message popped up stating that "Callback function is not a fu ...

The Angular Nativescript framework is lacking necessary properties for the 'Observable<>' type

Whenever I try to set my function as getCalendarEvents(): Observable<Array<CalendarEvent>>{, I encounter an error message stating Type 'Observable<CalendarEvent[]>' is missing the following properties from type 'CalendarEve ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Having trouble with Angular deeplinks - my app is opening but the routing isn't working as expected

Help needed: I'm facing an issue with deeplinks in my app where the routing is not working properly. Below is the code snippet causing the problem: import { Component, ViewChild } from ‘@angular/core’; import { App, Platform, Nav, NavController ...

Tips for utilizing ion-img within an Ionic 3 application?

I am currently developing an app using Ionic 3 that includes a large number of images spread across different pages. Initially, I used the default HTML image tag to display these images. However, this approach caused lag in the app's performance and a ...

Unable to send a function as props to a child component in TypeScript

Within my application, I have a parent component that holds a state and a setState function. This state and function are then passed down to a child component in order to retrieve values (such as input field data). When the function is triggered in the chi ...

Removing the AM and PM from OwlDateTime in Angular is simple since the time format is already in 24-hour time

Using OwlDateTime in a 24-hour format: <div *ngIf="isSchedule" class="form-inline"> <label style='margin-right:5px ;margin-left:210px'> Date Time: <input [owlDateTimeTrigger]="dt" [owlDateTime]="dt" class="form-control" placeh ...