Search code examples
angulartypescriptangular-reactive-formsangular-forms

How to add data in formArray from JSON response in Angular?


I have a JSON response coming from firebase, but when I load the page it display only first array in formArray rather than multiple fields. Please check my code below and guide me where I am wrong.

Here is the snapshot of my response coming from firebase.

enter image description here

Code

 ngOnInit(): void {
    this.loadForm();
    this.questionService.getQuestion(this.id).subscribe((res) => {
      this.editQuestionForm.patchValue({
        question: res.payload.data()['question'],
        type: res.payload.data()['type'],
        next_question: res.payload.data()['next_question'],
        actions: res.payload.data()['actions'],
      });
    });
   }

  loadForm() {
    this.editQuestionForm = this.fb.group({
      question: ['', Validators.required],
      type: ['', Validators.required],
      actions: this.fb.array([this.createActionFields()]),
      next_question: ['', Validators.required],
    });
  }

  action_fields(): FormArray {
    return this.editQuestionForm.get('actions') as FormArray;
  }

  createActionFields(): FormGroup {
    return this.fb.group({
      field: '',
      response: '',
    });
  }

  addActionFields() {
    this.action_fields().push(this.createActionFields());
  }

  removeActionFields(index) {
    this.action_fields().removeAt(index);
  }

And here is the output coming

enter image description here

Please check my above code and guide me, what can i do for display proper data.


Solution

  • you need to have a controls in actions the same size of the responds actions if the actions respond.

    as example if the respond return array of 5 fields you need to addActionFields() five time because you use patchValue you will not get an error but it you use setValue you will see and error.

    this.questionService.getQuestion(this.id).subscribe((res) => {
        const actions = res.payload.data()['actions'];
        action.forEach( () =>{
          this.addActionFields();
        });
    
       this.editQuestionForm.patchValue({
         question: res.payload.data()['question'],
         type: res.payload.data()['type'],
         next_question: res.payload.data()['next_question'],
         actions
       });
     });