0

I'm having an issue trying to work with multiple checkboxes i bring from the backend:

First i need that the data selected by the user from checkboxes sends to the back, but only i have object: "0:" in the payload console. I am using Angular v13 as a front-end with Reactive Forms. So i will ask for a hand.

This is the code:

TS

conocimientosInformatica: string[] | undefined;

//This function brings the data from API

getDatos() {
    this.alta_service.getInscripcion()
      .subscribe((data: any) => {
        const conocimientosInformatica = data.formacion.estudios.conocimientos_de_informatica;
        this.conocimientosInformatica = Object.keys(conocimientosInformatica["#options"]);
        console.log(this.conocimientosInformatica);
        });
      }
      


//I got the data from conocimientos_de_informatica field in the backend

get conocimientos_de_informatica() { return this.educationAndSkills.get('conocimientos_de_informatica') as FormArray };
   

//And Created myFormBuilder
    
   educationAndSkills = this.formBuilder.group({
      conocimientos_de_informatica: this.formBuilder.array([''])
   })

This is the output:

(4) ['Procesadores de texto', 'Planillas de cálculo', 'Software de gestión', 'Otros']

In my HTML View i put it like this:

<div class="fieldset-wrapper">
   <div class="js-webform-checkboxes webform-options-display-one-column form-checkboxes" *ngFor="let informatica of conocimientosInformatica; index as i" formArrayName="conocimientos_de_informatica">
      <div class="js-form-item form-item js-form-type-checkbox form-type-checkbox js-form-item-conocimientos-de-informatica">
         <input type="checkbox" name="conocimientos_de_informatica" [formControlName]="i" value="{{informatica}}" class="form-checkbox">
         <label for="edit-conocimientos-de-informatica-checkboxes" class="option">{{informatica}}</label>
      </div>
   </div>
</div>

Tried other several ways posted here, but don't apply in my case because here the Array of checkboxes are brought via the API. I need to send the data checked to the Backend results.

I would appreciate your help.

HomerO
  • 33
  • 2
  • 14

2 Answers2

0

1. Synchronize FormArray with Received Data

To synchronize the FormArray with received data, create the form after fetching data from the server. Use false to initialize boolean values:

this.fakeData$.subscribe((cdi: string[]) => {
  this.cdi = cdi;
  this.form = this.fb.group({
    cdi: this.fb.array(cdi.map((e) => false)),
  });
})

2. Print FormArray Using formArrayName

To print the FormArray, use formArrayName instead of formControlName:

<div *ngFor="let name of cdi; let i = index" formArrayName="cdi">
  <input type="checkbox" [formControlName]="i">
  <span>{{name}}</span>
</div>

3. Obtain Textual Values of Indexes with True Values

In the submission phase, use map and filter to obtain textual values of indexes with true values:

onSubmit() {
  this.results = {
    ...this.form.value, 
    ...{
      cdi: this.form.value.cdi
        .map((x:boolean, i:number) => x && this.cdi[i])
        .filter((x:boolean) => !!x),
      }
    }
  }
}

Check how it works. I created a Stackblitz for you.

0

If you are struggling to construct reactive forms based on a response from the API using formBuilder.array please see this answer here.

Dynamic form using *ngFor and submitting values from it


If you are having issues getting values from the FormGroup see below.

There is a native function and property on the FormGroup class that allows you to get values from your FormGroup controls.

Using FormGroup.value returns all FormGroup values from enabled controls.

https://angular.io/api/forms/AbstractControl#value

Using the FormGroup.getRawValue() function returns all FormGroup values regardless of the control disabled state.

https://angular.io/api/forms/FormGroup#getRawValue

console.log(conocimientosInformatica.value);
// or
console.log(conocimientosInformatica.getRawValues()); 
Marshal
  • 10,499
  • 2
  • 34
  • 53