lundi 9 septembre 2019

Select all checkbox reactive forms Angular 8

I have multiple checkbox arrays in my checkbox form. When user clicks select all button I need to select all checkbox.By using reactive forms and FormArray this is what I had tried:

Ts file

  get formReceivedSummons() {
    return this.form.get('receivedSummons') as FormArray;
  }

  formReceivedSummonsItems(i: number) {
    return (this.formReceivedSummons.controls[i].get('items')) as FormArray;
  }

  constructor(private inquiryStore: InquiryStoreService, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      receivedSummons: this.formBuilder.array([])
    });
    this.getReceivedSummons();
  }

  getReceivedSummons() {
    this.inquiryStore.summons$.subscribe(result => {
      this.receivedSummon = result;
      this.addCheckboxes();
    });
  }

  selectAllCheckbox() {
    this.formReceivedSummons.controls.map(value => value.setValue(true));
  }

  addCheckboxes() {
    this.formReceivedSummons.setValue([]);
    this.receivedSummon.data.items.map(x => {
      const group = this.formBuilder.group({
        header: [this.receivedSummon.header],
        items: this.formBuilder.array([], [minSelectedCheckboxes(1)])
      });
        (group.get('items') as FormArray).push(this.formBuilder.group({
          name: [x.itemNo],
          isChecked: [false, Validators.required]
        }));
      this.formReceivedSummons.push(group);
    });
  }

Html file

    <form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
      <ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
        <ng-container [formGroup]="summon">
          <ng-container formArrayName="items" *ngFor="let item of formReceivedSummonsItems(i).controls; let j = index">
            <ng-container [formGroup]="item">
              <input type="checkbox" formControlName="isChecked"> 
            </ng-container>
          </ng-container>
        </ng-container>
      </ng-container>
      <br>
    </form>
  <button (click)="selectAllCheckbox()">SELECT ALL</button>

I got error when I'm try to select all:

Error: Must supply a value for form control with name: 'header'.

I could not figure out what the errors and could use some guidance and suggestion.




Aucun commentaire:

Enregistrer un commentaire