Issue: The formGroup function requires a valid FormGroup instance to be passed in. Data retrieval unsuccessful

My goal is to retrieve user data from a user method service in order to enable users to update their personal information, but I'm encountering an error. Currently, I can only access the "prenom" field, even though all the data is available as seen in the photo below. Here's my code:

UserProfil.TS:

 export class UserProfileComponent implements OnInit {
      public _contactForm: FormGroup;

      constructor(
        private userSeervice: UserService,
        private tokenStorage: TokenStorageService,
        private _formBuilder: FormBuilder
      ) {}

      ngOnInit() {
        const id = this.tokenStorage.getUser().id;
        this.userSeervice.getUser(id).subscribe(data => {
          this._contactForm = this._formBuilder.group({
            id: [data.id],
            nom: [data.nom, [Validators.required]],
            prenom: [data.prenom, [Validators.required]],
            email: [data.email, [Validators.required]],
            username: [data.username, [Validators.required]]
          });
        });
      }
    }

UserPofile.HTML

<div class="main-content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12">
        <div class="card" data-aos="fade-right">
          <div class="card-header ">
            <h4 class="card-title">Edit Profile</h4>
            <p class="card-category" style="color:white;">
              complete your profile
              {{ _contactForm.value | json }}
            </p>
          </div>
          <div class="card-body">
            <form [formGroup]="_contactForm">
              <div class="row">
                <div class="col-md-3">
                  <mat-form-field class="example-full-width">
                    <input
                      matInput
                      formControlName="username"
                      placeholder="Username"
                    />
                  </mat-form-field>
                </div>
                <div class="col-md-4">
                  <mat-form-field class="example-full-width">
                    <input
                      matInput
                      formControlName="email"
                      placeholder="Email Address"
                      type="email"
                    />
                  </mat-form-field>
                </div>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <mat-form-field class="example-full-width">
                    <input
                      matInput
                      formControlName="nom"
                      placeholder="Last Name"
                      type="text"
                    />
                  </mat-form-field>
                </div>
                <div class="col-md-6">
                  <mat-form-field class="example-full-width">
                    <input
                      matInput
                      formControlName="prenom"
                      placeholder="First Name"
                      type="text"
                    />
                  </mat-form-field>
                </div>
              </div>

              <button
                mat-raised-button
                type="submit"
                style="background-color: #09c0a3;"
                class="btn  pull-right"
                (click)="update(_contactForm.value.id)"
              >
                Update Profile
              </button>
              <div class="clearfix"></div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Additionally, here is a photo for clarity:

The JSON format shows that all data is available, yet I am unable to retrieve it.

Answer №1

The reason for the issue is that your form is being loaded asynchronously.

To solve this, you can delay rendering the form until the service returns the data.

<form *ngIf="_contactForm" [formGroup]="_contactForm">
  <!-- your form content -->
</form>

The error occurs because you are initially passing undefined into the [formGroup].

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

The speed of Mean Stack API calls leaves much to be desired

Our team has developed a MEAN stack application that functions smoothly on the client side. However, we have been facing issues with slow API requests and responses on the server side. For example, when a request is sent from Angular, it takes an average ...

Creating a CSS class in a separate file for an element in Angular 4

Looking for some help with my code setup. Here's what I have: <div class="over"> Content </div> In my component file, this is what it looks like: @Component({ selector: 'app', templateUrl: './app.componen ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

Create a Typescript index signature that incorporates individual generic types for each field

Many times, the keys of a record determine its value. For instance: const record = { [2]: 5, ["string"]: "otherString", ["there is"]: "a pattern" } In these instances, each key of type K corresponds to the ...

An error occurred with useState and localStorage: the parameter type 'string null' cannot be assigned to a parameter of type 'string'

I am currently using NextJS and attempting to persist a state using localStorage. Here is my code implementation: const [reportFavorite, setReportFavorite] = useState([ 'captura', 'software', 'upload', ] as any) ...

ngFor loop is not displaying the correct values from the JSON object

Having some trouble making a REST call and displaying the results obtained. I've managed to successfully work with a simpler JSON data structure, but I'm struggling to get ngFor to properly process this particular data structure. I've tried ...

"An issue arises as the variable this.results.rulesFired is not properly

I am faced with a set of table rows <tr *ngFor="let firedRule of splitRules(results.rulesFired); let rowNumber = index" [class.added]="isAdd(firedRule)" [class.removed]="isRemove(firedRule)" ...

Can someone provide guidance on utilizing parentheses in HTML code?

I am facing an issue in my Angular project while using the WordPress API. The problem lies in the API address structure which includes "" like this: <img src="{{importantvideo.better_featured_image.media_details.sizes.["covernews-med ...

A guide on transferring files to a PHP server using HttpClient and FormData within an Ionic framework, along with instructions on receiving files in PHP

I have an input file in mypage.html on Ionic and I want to send this file to PHP for uploading it onto the server. In mypage.page.html, I have created an input field for the file name and another input field for the file to be uploaded. <ion-header> ...

Tips on storing and retrieving data between pages in Ionic 4/5: Saving data to a service and accessing it from a

Looking for assistance from the community I am trying to pass data between pages using a service in Angular. Here is the code for the parent component.ts file: import { Component } from '@angular/core'; import { ShareService } from '../sh ...

Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are: all generated values must be distinct the order of values remains consistent upon each run of the generator each value should be significantly diff ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

Underwhelming scroll speed when working with 9 columns in react-virtualized

I am currently utilizing react-virtualized in conjunction with material-ui table cells to establish a table featuring virtual scrolling. Although everything appears to be functioning correctly, I am experiencing intermittent performance slowdowns when navi ...

React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to ...

Incorporating map, forkJoin, and mergeMap into your code base can

I have a requirement to perform multiple API calls. The first API call returns a list of objects with the properties userId and propertyId. For each item in this list, I need to fetch additional information called userInfo and propertyInfo based on the I ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...