How to make a FormGroup optional(nullable) inside another FormGroup all strongly typed? (StackBlitz indside)

98 Views Asked by At

https://stackblitz.com/edit/angular-formgroup-optional?file=src%2Fmain.ts,src%2Fform%2Fform.component.ts

So i have a strongly type formgroup like so:

export interface BasicForm {
  id: FormControl<string | null>;
  setting: FormControl<number>;
  optionalGroup: FormGroup<OptionalGroup | null>; // make optional (null if not needed) is setting is not 1
}

export interface OptionalGroup {
  id: FormControl<string>;
  name: FormControl<string>;
}

Created with the formBuilder like so:

this.formBuilder.group<BasicForm>(
      {
        id: new FormControl(''),
        setting: new FormControl(0, {
          nonNullable: true,
          validators: Validators.required,
        }),

        // make required if setting is 1
        // otherwise null
        optionalGroup: this.formBuilder.group<OptionalGroup>({
          id: new FormControl('', {
            nonNullable: true,
            validators: Validators.required,
          }),
          name: new FormControl('', {
            nonNullable: true,
            validators: Validators.required,
          }),
        }) as FormGroup<OptionalGroup | null>,
      },
      {
        validators: [optionalGroupValidator(this.formBuilder)],
      }
    );

I want to accomplish this with a custom Validator:

export function optionalGroupValidator(formBuilder: FormBuilder): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const basicForm = control as FormGroup<BasicForm>;

    const validatorErrors: ValidationErrors = {};

    if (basicForm.controls.setting.value === 1) {
      const newForm = formBuilder.group<OptionalGroup>({
        id: new FormControl('', {
          nonNullable: true,
          validators: Validators.required,
        }),
        name: new FormControl('', {
          nonNullable: true,
          validators: Validators.required,
        }),
      });

      //Add the formback or?
      //  basicForm.addControl('optionalGroup', newForm);
    } else {
      //basicForm.controls.optionalGroup.setValue(null);
    }

    console.log(basicForm);

    return validatorErrors;
  };
}

I' cant get the validator to work, or i don't know how the logic should be. Do i remove it from the controls? or just make it not required? I've tried both but can not get it to work.

The end result i want:

this.basicForm.getRawValue(); // optionalGroup should be omitted or null if setting is  not 1

Stackblitz is ready to go:

https://stackblitz.com/edit/angular-formgroup-optional?file=src%2Fmain.ts,src%2Fform%2Fform.component.ts

0

There are 0 best solutions below