disable FormGroup by using Validators

前端 未结 2 1955
广开言路
广开言路 2021-01-26 11:00

I had formArray checkbox on my checkboxForm, I need to disabled button submit if no checkbox are checked, I had implement custom validator

相关标签:
2条回答
  • 2021-01-26 11:22

    Make something like this:

    export a function. something like this:

    export function customValdiator(form: FormGroup) {
      const formValue = form.value;
      // with the formValue apply your own validation logic .
      if (/* HAVE ERROR */) {
        return { checkboxesRequired: true };
      } else {
        return null;
      }
    }
    

    build your form:

     this.checkboxForm = this.formBuilder.group({
          receivedSummons: this.formBuilder.array([])
        },  { validator: customValdiator });
    

    and remove add validators from your addCheckboxes method.

    dont matter if u add or remove rows to receivedSummons FormArray when u change any data on the form angular will execute customValdiator function and pass the form as argument and you have access to current receivedSummons values for valid which is checked.

    0 讨论(0)
  • 2021-01-26 11:30

    When you are initializing the form in the constructor add the validator to the formarray first.Then after you receive the data call the addCheckboxes method.

    form: FormGroup;
    receivedSummons = [];
    
    constructor(private formBuilder: FormBuilder) {
       this.checkboxForm = this.formBuilder.group({
         receivedSummons: new FormArray([], minSelectedCheckboxes(1))
       });
    
       of(this.someMethodWhichReturnReceivedSummons()).subscribe(receivedSummons => {
          this.receivedSummons = receivedSummons;
          this.addCheckboxes();
       });
    }
    

    In the addCheckboxes

    private addCheckboxes() {
        this.receivedSummons.map((o, i) => {
          const control = new FormControl(i === 0); // if first item set to true, else false
          (this.form.controls.receivedSummons as FormArray).push(control);
        });
    }
    
    0 讨论(0)
提交回复
热议问题