Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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": "max-mustermann@gmail.com"
    },
    "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>

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório

0

FormBuilder control takes an object containing default value and disabled state or just the default value so update your generate form method like this:

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

And where your are calling this function you need to pass the currentUser

this.generateUserFormGroup(data[0].currentUser)

Check this

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda