gparlakov/forms-typed

forms-utils: add the async validators up the chain

gparlakov opened this issue · 1 comments

When using the forAllControlsIn and addValidatorsTo the async validators are not supported.

Perhaps :

    addValidatorsTo(parentControl: AbstractControl | null | undefined) {
      if (parentControl != null) {
        parentControl.validator = Validators.compose([
          parentControl.validator,
          () => {
            // could overwrite some errors - but we only need it to communicate to the "parent" form that
            // these controls here are valid or not
            const errors = controls.reduce((e, next) => ({ ...e, ...next.errors }), {});

            return controls.some(c => c.errors != null) ? errors : null;
          }
        ]);

        parentControl.asyncValidator = Validators.composeAsync([
          parentControl.asyncValidator,
          async (c) => {

            return Promise.all(controls
                .filter(c => typeof c?.asyncValidator ==='function')
                .map(c => typeof c?.asyncValidator ==='function' ? isObservable(c.asyncValidator(c) : Promise.resolve()
              )
              .then((results: (object | null)[]) => results.filter(o => o != null))


          }
        ])
      }

      return composer;
    }