0

I have array (gifts) of objects, after filled valid form by user, I want to check which checkboxes are checkIn, next push name of selected gifts into giftsArr and on submit-action push into gifts FormArray. I don't have idea how to do it.

 gifts = [
    {
      text: 'Pack as a gift',
      isClick: false,
    },
    {
      text: 'Add postcard',
      isClick: false,
    },
    {
      text: 'Provide 2% discount to the next time',
      isClick: false,
    }
]
ngOnInit() {
  this.signupForm = new FormGroup({
    gifts: new FormArray([]),
  });
  onSubmit() {
    const checkedGifts = this.gifts.filter((gift) => gift.isClick === true);
    const giftsArr: any = [];
    checkedGifts.forEach((gift) => giftsArr.push(gift.text));

    // console.log(giftsArr) => ['Pack as a gift', 'Add postcard'];
  }

1 Answer 1

0

You need to initialize each gift object as FormGroup instance in gifts FormArray.

ngOnInit() {
  this.signupForm = new FormGroup({
    gifts: new FormArray([]),
  });

  this.initGiftsArrayControl();
}

initGiftsArrayControl() {
  for (let gift of this.gifts) {
    let formGroup = new FormGroup({
      name: new FormControl(gift.text),
      value: new FormControl(gift.isClick),
    });

    this.giftsArrayControl.push(formGroup);
  }
}

get giftsArrayControl() {
  return this.signupForm.controls.gifts as FormArray;
}

getGiftName(control: AbstractControl<any, any>) {
  return (control as FormGroup).controls.name.value;
}

Next, the HTML template should be rendered each control from gifts FormArray as below:

<div [formGroup]="signupForm">
  <div formArrayName="gifts">
    <div *ngFor="let control of giftsArrayControl.controls; let i = index;">
      <ng-container [formGroupName]="I">
        <input type="checkbox" formControlName="value" />
        <label>{{ getGiftName(control) }}</label>
      </ng-container> 
    </div>
  </div>

  <button type="submit" (click)="onSubmit()">Submit</button>
</div>

Lastly, to get the checked gift(s) by filtering the object with value: true:

onSubmit() {
  const checkedGifts = this.giftsArrayControl.value
    .filter((gift: any) => gift.value)
    .map((gift: any) => gift.name);

  console.log(checkedGifts);
}

Demo @ StackBlitz

Sign up to request clarification or add additional context in comments.

2 Comments

Thre're not a good reason to create a formArray of FormGroup with the "value" and the "name". It's a well known problem. See one solution in this SO. Really it's not necessary use a FormArray, we can use [(ngModel)] like this another one
Hi @Eliseo, ya, seems I make it too complicated. Anyways thanks for the suggestion with the sample answers. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.