lundi 19 avril 2021

How to POST specific data from mat-checkbox? Angular app

I have problem with sending specific data from mat-checkbox. I need sending Array with selected values but now I send only true or null value.

Example:

I want to send such data after clicking on the specific checkboxes:

selectedValue: [4055, 4065, 4056, 4075]

id: "dasdasdas451622386"

Now I send this:

selectedValue: true (if I click on checkbox, if I don't click o check box value is null)

id: "dasdasdas451622386"

My code:

component.html

    <div class="row">
            <div class="col-md-4">
              <form [formGroup]="selectEquipments" (submit)="submitForm()">
                <input formControlName="id" [(ngModel)]="selectedId" hidden>
                <section *ngFor="let item of optionItems.optionalEquipment">
                  <mat-checkbox
                    formControlName="selectedValue"
                    (change)="changeSelection()"
                    [value]="item.code"
                  >
                     - 
                  </mat-checkbox>
                </section>
              </form>

              <button
                   mat-raised-button
                   (click)="submitForm()"
              >
              Submit
              </button>
            </div>
    </div>

component.ts

equipmentsResults: EquipmentsResults[] = [];
selectedItemsList = [];
checkedIDs = [];
selectedId: string | null = null;

 constructor(
    private formBuilder: FormBuilder,
  {}

ngOnInit(): void {
    this.selectEquipments = this.formBuilder.group({
      id: [this.selectedId],
      selectedValue: []
    });
    this.fetchSelectedItems();
    this.fetchCheckedIDs();
  }

changeSelection() {
this.fetchSelectedItems();
}

fetchSelectedItems() {
    this.fetchCheckedIDs();
    this.selectedItemsList = this.equipmentsResults.filter((value, index) => {
      return value.optionalEquipment?.selected;
    });
  }

fetchCheckedIDs() {
    this.checkedIDs = [];
    this.equipmentsResults.forEach((value, index) => {
      if (value.optionalEquipment?.selected) {
        this.checkedIDs.push(value.optionalEquipment.code);
      }
    });
  }

submitForm() {
    this.apiService.selectEquipment(this.selectEquipments?.value)
      .subscribe(
        (response: any) => {
          this.equipmentsResults = JSON.parse(response);
        },
      );
  }

model.ts

    export class EquipmentsResults {
      id: string | null = null;
      idHash: string | null = null;
      txid: string | null = null;
      optionalEquipment: OptionalEquipment | null = null;
    
      constructor() {}
    }

export class OptionalEquipment {
  code: number | null = null;
  description: string | null = null;
  group: string | null = null;
  selected: boolean | null = null;
}



Aucun commentaire:

Enregistrer un commentaire