Search code examples
angulartypescriptangular-reactive-formsformarray

Data from the JSON is not displayed in the inputs of the FormArray


I have a JSON and would like to output the data from this object to the FormArray. I am only getting Object object displayed in the output. What is the best way to solve this problem and what can I do better in building the code?

My StackBlitz: https://stackblitz.com/edit/get-data-from-api-and-populate-form-array-with-it-5kjunq?file=src%2Fapp%2Fapp.component.html

My code:

// My JSON
[
  {
    "currentUser": {
      "userId": 2,
      "gender": "Herr",
      "firstname": "Max",
      "lastname": "Mustermann",
      "username": "maxMustermann",
      "email": "[email protected]"
    },
    "success": true
  }
]
// My TS
 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 }),
    });
  }
// My 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>


Solution

  • Disclosure: I am not an Angular developer, I'm not sure if there are consequences to the use of new FormControl .

    First of all param is an object that contains another object called currentUser - there was an attempt to reach inaccessible fields.

    I followed their docs, seems to do the job -

      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)
        });
      }
    }
    

    enter image description here

    Reactive forms Angular docs