Home > Software design >  Array save in a Json structure – angular
Array save in a Json structure – angular

Time:01-12

Good day,I am doing an app on angular where create a flow of steps, I use angular material stepper for this; I need to save all the inputs in a json structure when the user finishes the all the steps, now I save all the inputs in the array but a don’t how transform the array to json structure like this.

{
    user: {
       "nombreCtrl":"Esperanza",
       "ap_paternoCtrl":"Wiesse ",
       "ap_maternoCtrl":"Gutierrez",
       "dniCtrl":"123456"
    },
    adress: {
       "regionCtrl":"Cusco",
       "provinciaCtrl":"Cusco",
       "distritoCtrl":"Cusco",
       "dirrecionCtrl":"sdfg"
    },
    pay: {
       "targeraCtrl":"1234567890",
       "seguridadCtrl":"234"
    }
 }

This is my code on angular (this code is an example that illustrates what I am trying to do).

pay.component.html

<form [formGroup]="formGroup" (ngSubmit)="submit(formGroup.value)">
  <mat-stepper #stepper formArrayName="formArray"  >
    <!-- paso 1 -->
    <mat-step  errorMessage="Name is required." formGroupName="0" [stepControl]="formArray?.get([0])!">


        <!-- nombre del paso -->
        <ng-template matStepLabel>Fill out your name</ng-template>

        <!-- input -->
        <mat-form-field appearance="fill">
          <mat-label>Nombre</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="nombreCtrl" required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>Apellido paterno</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="ap_paternoCtrl" required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>Apellido materno</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="ap_maternoCtrl" required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>DNI</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="dniCtrl" required>
        </mat-form-field>

        <!-- button -->
        <div>
          <p>Go to a different step to see the error state</p>
          <button type="button"  mat-button matStepperNext>Next</button>
        </div>

      
    </mat-step>
    <!-- paso 1 end  -->

    <!-- paso 2 -->
    <mat-step  errorMessage="Address is required."  formGroupName="1" [stepControl]="formArray?.get([1])!">


         <!-- nombre del paso -->
        <ng-template matStepLabel>Dirrecion de entrega</ng-template>

        <!-- input -->
        <mat-form-field appearance="fill">
          <mat-label>Region</mat-label>
          <input matInput placeholder="Ex. 1 Main St, New York, NY" formControlName="regionCtrl"
                 required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>Provincia</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="provinciaCtrl" required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>Distrito</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="distritoCtrl" required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>Dirreccion</mat-label>
          <input matInput placeholder="Last name, First name" formControlName="dirrecionCtrl" required>
        </mat-form-field>

        <!-- button -->
        <div>
          <p>Go to a different step to see the error state</p>
          <button type="button" mat-button matStepperPrevious>Back</button>
          <button type="button" mat-button matStepperNext>Next</button>
        </div>
      
    </mat-step>
    <!-- paso 2 end -->

    <!-- paso 3 -->
    <mat-step  errorMessage="Address is required."  formGroupName="2" [stepControl]="formArray?.get([2])!">


         <!-- nombre del paso -->
        <ng-template matStepLabel>Pay your order</ng-template>

        <!-- input -->
        <mat-form-field appearance="fill">
          <mat-label>numero de targeta de credito</mat-label>
          <input matInput placeholder="Ex. 1 Main St, New York, NY" formControlName="targeraCtrl"
                 required>
        </mat-form-field>
        <br>
        <mat-form-field appearance="fill">
          <mat-label>numero de seguridad </mat-label>
          <input matInput placeholder="Ex. 1 Main St, New York, NY" formControlName="seguridadCtrl"
                 required>
        </mat-form-field>

        <!-- button -->
        <div>
          <p>Go to a different step to see the error state</p>
          <button type="button" mat-button matStepperPrevious>Back</button>
          <button type="button" mat-button matStepperNext>pagar</button>
        </div>
      
    </mat-step>
    <!-- paso 3 end -->

    <!-- paso 4 -->
    <mat-step>
      <ng-template matStepLabel>Done</ng-template>
      <p>su compra fue exitosa</p>
      <div>
        <button mat-button matStepperPrevious>Back</button>
        <button mat-button  type="submit" >Done</button>
        <button mat-button (click)="stepper.reset()">Reset</button>
      </div>
    </mat-step>
    <!-- paso 4 end -->

  </mat-stepper>
  
</form>

pay.component.ts

export class PayComponent implements OnInit {

  formGroup !: FormGroup ;      

  constructor(
    private _formBuilder: FormBuilder,
    public _payService: PayService
  ) {}

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          nombreCtrl: ['', Validators.required],
          ap_paternoCtrl: ['', Validators.required],
          ap_maternoCtrl: ['', Validators.required],
          dniCtrl: ['', Validators.required],
        }),

        this._formBuilder.group({
          regionCtrl: ['', Validators.required],
          provinciaCtrl: ['', Validators.required],
          distritoCtrl: ['', Validators.required],
          dirrecionCtrl: ['', Validators.required]
        }),

        this._formBuilder.group({
          targeraCtrl: ['', Validators.required],
          seguridadCtrl: ['', Validators.required]
        }),
      ])

     
    });
  }


  get formArray(): AbstractControl | null { 
    return this.formGroup.get('formArray'); 
  } 

  submit(f: FormGroup) {
    if (f.invalid) {
      return;
    }
    
    // transform array in json
    let jsonPay = JSON.stringify(f);
    
  }

When I transform the array in json, it has this structure, but it not the structure that i want. I don't know how modify this structure.

{
    "formArray":[
       {
          "nombreCtrl":"Esperanza",
          "ap_paternoCtrl":"Wiesse ",
          "ap_maternoCtrl":"Gutierrez",
          "dniCtrl":"123456"
       },
       {
          "regionCtrl":"Cusco",
          "provinciaCtrl":"Cusco",
          "distritoCtrl":"Cusco",
          "dirrecionCtrl":"sdfg"
       },
       {
          "targeraCtrl":"1234567890",
          "seguridadCtrl":"234"
       }
    ]
 }

CodePudding user response:

In order for you to have expected json structure, there is no need of using FormArray.

You can define this.formGroup as:

this.formGroup = this._formBuilder.group({
  user: this._formBuilder.group({
    nombreCtrl: ['', Validators.required],
    ap_paternoCtrl: ['', Validators.required],
    ap_maternoCtrl: ['', Validators.required],
    dniCtrl: ['', Validators.required],
  }),

  adress: this._formBuilder.group({
    regionCtrl: ['', Validators.required],
    provinciaCtrl: ['', Validators.required],
    distritoCtrl: ['', Validators.required],
    dirrecionCtrl: ['', Validators.required]
  }),

  pay: this._formBuilder.group({
    targeraCtrl: ['', Validators.required],
    seguridadCtrl: ['', Validators.required]
  })
});

and adjust the html template as:

<mat-stepper #stepper>   <!-- Removed formArrayName="formArray" -->
  <mat-step errorMessage="Name is required." formGroupName="user" [stepControl]="formGroup?.get('user')!">   <!-- Updated formGroupName and [stepControl] values -->
      <!-- No change, remains as it is -->
  </mat-step>
  <mat-step errorMessage="Address is required."  formGroupName="adress" [stepControl]="formGroup?.get('adress')!">   <!-- Updated formGroupName and [stepControl] values -->
    <!-- No change, remains as it is -->
  </mat-step>
  <mat-step  errorMessage="Pay is required."  formGroupName="pay" [stepControl]="formGroup?.get('pay')!">   <!-- Updated formGroupName and [stepControl] values -->
    <!-- No change, remains as it is -->
  </mat-step>
</mat-stepper>
  •  Tags:  
  • Related