The inputs in the FormArray are not populated with the data from the JSON

I am struggling with outputting data from a JSON object to a FormArray. When I try to display the data, all I get is Object object. Can anyone suggest the best way to tackle this issue and offer advice on improving my code?

Here is the StackBlitz link to my project: StackBlitz

Below is my code:

// JSON Data
[
  {
    "currentUser": {
      "userId": 2,
      "gender": "Herr",
      "firstname": "Max",
      "lastname": "Mustermann",
      "username": "maxMustermann",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3558544d1858404641504758545b5b755258545c591b565a58">[email protected]</a>"
    },
    "success": true
  }
]
// TypeScript Code
 userForm: FormGroup;

  constructor(private fb: FormBuilder, private http: HttpClient) {}

  ngOnInit() {
    this.http.get('/assets/data.json').subscribe((resp: any[]) => {
      const data = resp;
      if (data && data !== null) {
        console.log('Output', data);
        this.userForm = this.fb.group({
          userFormArray: this.fb.array(
            resp.map((param) => this.generateUserFormGroup(param))
          ),
        });
      }
    });
  }

  private generateUserFormGroup(param) {
    return this.fb.group({
      gender: this.fb.control({ value: param.gender }),
      firstname: this.fb.control({ value: param.firstname }),
      lastname: this.fb.control({ value: param.lastname }),
      username: this.fb.control({ value: param.username }),
      email: this.fb.control({ value: param.email }),
    });
  }
// HTML Template
<form [formGroup]="userForm">
  <div formArrayName="userFormArray">
    <div
      *ngFor="
        let control of userForm.controls['userFormArray'].controls;
        let i = index
      "
    >
      <div [formGroupName]="i">
        <input type="text" formControlName="gender" />
        <input type="text" formControlName="firstname" />
        <input type="text" formControlName="lastname" />
        <input type="text" formControlName="username" />
        <input type="text" formControlName="email" />
      </div>
    </div>
  </div>
</form>

Answer №1

Disclaimer: I do not specialize in Angular development, so I cannot definitively say if the use of new FormControl carries any repercussions.

In this scenario, the param object contains a nested object named currentUser, which led to attempts to access inaccessible fields.

After reviewing their documentation, it appears to be functioning as intended -

  private generateUserFormGroup(param) {
    const { currentUser } = param;
    return this.fb.group({
      gender: new FormControl(currentUser.gender),
      firstname: new FormControl(currentUser.firstname),
      lastname: new FormControl(currentUser.lastname),
      username: new FormControl(currentUser.username),
      email: new FormControl(currentUser.email)
    });
  }
}

https://i.sstatic.net/oot6a.png

Explore Reactive Forms in Angular's official documentation

Answer №2

FormBuilder control function is used to handle default values and disabled states in an object or just the default value. Update your form generation method as shown below:

private createFormGroup(param) {
 return this.fb.group({
  gender: this.fb.control(param.gender),
  email: this.fb.control({ value: param.email, disabled: false }),
 });
}

Make sure to pass the currentUser when calling this function.

this.createFormGroup(data[0].currentUser)

For more information, visit this link

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

Assign a property name in an interface based on the value of another property

Is there a way to define a list of permitted values for a property name in an interface? Let's consider an interface as an example: export interface DashboardRequest { name?: string; description?: string; type: 'foo' | 'bar&apos ...

What is the correct way to properly cancel a request?

Imagine a scenario where I am utilizing a service that sends HTTP requests to my API and returns observables, which is pretty common. While using this service, the user might become impatient and decide to cancel the request by calling my-subscription.uns ...

Is it possible to utilize rxjs to exclude elements from an Observable based on a string array of identifiers?

When configuring Access Control for my Angular app, I have structured the User object as follows: -User --firstName --phoneNumber --posts[] <--- String array of post id's getPosts(): Observable<any[]> { return this.postsCollection.snap ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Automatically reloading clients after deployment with Angular 10 for enhanced user experience

As of now, my application is live with all the JavaScript files having a timestamp version. However, when I rebuild my Angular app, the JavaScript files will be updated with a new timestamp version. https://i.stack.imgur.com/M8MDN.png Is there a method t ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Error message in Angular Console: ERROR - Unable to access properties of an undefined value while attempting to read 'data'

The Console is showing an error: ERROR TypeError: Cannot read properties of undefined (reading 'data") at Oviewer Component 15A11Selected (oviewer.component.ts:97:37) at OviewerComponent.checkbeaLabel (aviewer.component.ts:114:22) at Oviewer C ...

Ionic 5 Error: Unable to access 'subscribe' property of undefined object

Working with IONIC 5 service: import { HttpClient } from '@angular/common/http'; . . . getPlaces(placeId: string) { return this.httpClient.get( `https://test.com/offered-place/${placeId}.json`) } . . . Encountering an issue when tryin ...

What is the best method for connecting an Angular 2 application with an existing Angular JS app?

I recently created an application using Angular 2 and now I am looking to combine it with an Angular JS app. ...

Is it possible to modify the stroke color of the progress circle in ng-zorro?

I am working on an Angular project where I aim to create a dashboard displaying various progress circles. Depending on the progress, I need to change the color of the line. Current appearance: https://i.sstatic.net/hR2zZ.png Desired appearance: https://i. ...

The parameter type '1' cannot be assigned to the parameter type 'number[]'

Currently, I am delving into the services of Angular4 while using it. Despite ensuring that everything is correctly set up in my dataServices class, I keep encountering an error related to the argument passed to observer.next(1); I would appreciate any in ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Exploring the functionalities of React Native with react-hook-form and implementing them with TypeScript

I've been working on creating a custom Input component in react native using typescript for the react-hook-form library. type CustomInputProps = { name: any, control: any } const CustomInput: FC<CustomInputProps> = ({name, control, ...p ...

Using a variable within an Angular 2 Component provider

Is it possible for a component to offer a service based on its inputs? In my situation, my component relies on a service provided by another firebase service, and I am looking to have the component create a new firebase service with a child element, allowi ...

Can you explain the contrast between the two model configurations when making API calls?

Within my service file, I have a method that calls an API: getDetail(id: number): Observable<any> { return this.http.get<any>("api/detail/" + id, { responseType: 'json', observe: 'response' }) } Curren ...

Navigating an object in Typescript

I attempted to find some instructional materials, but unfortunately, they did not offer much useful information. Here is the JSX setup I am working with: Object: export const Project1 = [ { name: 'Interior Design Website', d ...

The value of NUMBER_VALUE cannot be transformed into a String while trying to update the Item

I've encountered a strange issue with DynamoDB where I'm unable to update an item. Below is the command I'm using: TableName: 'UserTable', Key: { UID: { S: 'h4XJj3YRxZiF7TDcGkxAhc' } }, UpdateExpression: 'SET numRat ...

Angular 4 router is being implemented for drag and drop functionality by ng-dragula with the

Our app is built with angular 4 and we are currently attempting to customize our theme using dragula. I successfully implemented all aspects of the page and everything seems to be working properly, including persistence. However, there is one major issue t ...

Combine the date and time into one variable

Is there a way to save the date and time fields in a variable with the format: 0000-00-00T00:00:00.000Z? component.html <mat-form-field appearance="outline" class="pr-sm-8" fxFlex="50"> <mat-label>Fecha Inicio ...

Converting the Angular 6 HTTP.get response to a string

When I call the GetServiceProviderId() function in my code, I am making a GET request to an API and expecting the result as a string that can be split. GetServiceProviderId() { this.http.get(this.rooturl + 'info', { headers: this.reqHeader ...