Home > Blockchain >  How to validate multiple select boxes in typescript
How to validate multiple select boxes in typescript

Time:09-30

Here's the scenario. I have a huge chunk of data which has the information about a product. The product has various options available without selecting all of them the user shouldn't be allowed to add the product to cart or buy. Here's the code I have tried.

this.form = new FormGroup({
      'options': new FormControl(null, [Validators.required]),
    });

This works fine but after selecting only 1 option the user is allowed to click on the add to cart button, I want to restrict that feature. I think I need to implement formArray . But I'm stuck here. I'll appreciate any help.

Here's the stackblitz for more details

CodePudding user response:

Initialize your form as

  initForm() {
    this.form = new FormGroup({
      options: new FormArray([]),
    });
  }

Helpers methods to get or set options

  set setOptionsFA(controls: FormControl[]) {
    controls.forEach((control) => this.optionsFA.push(control));
  }

  get optionsFA(): FormArray {
    return this.form.get('options') as FormArray;
  }

  get optionsControls(): FormControl[] {
    return this.optionsFA.controls as FormControl[];
  }

method to create FormControl[] out of your options list

  createOptionControls(options: any[]): FormControl[] {
    return options.map(
      (_) => new FormControl(null, Validators.required)
    ) as FormControl[];
  }

Use RxJs tap operator to call createOptionsControls method and pass options to it and set FormArray options

 this.appService
  .productDetail(247)
  .pipe(
    tap(
      ({ options }) =>
        (this.setOptionsFA = this.createOptionControls(options))
    )
  )
  .subscribe((res) => {
    this.data = res;
  });

Angular Demo

  • Related