0

I'm developing an angular application, in which i have a modal dialog with a form with some fields. In one of that i have an async validator to check if a value is just present in the DB calling a BE api.

My need is to trigger validation when i change the input of that field and when i submit the form.

Before the submiting of the form, i need to re-check all the fields, and i have to wait for the async-validator response, before say that the whole form is valid.

I've found a way to make this and it works very well.

    ...
    formSubmitSubject$ = new Subject();
    ...
     ngOnInit() {
     ....
      this.formSubmitSubject$
      .pipe(
        tap(() => this.form.markAsDirty()),
        switchMap(() =>
          this.form.statusChanges.pipe(
            startWith(this.form.status),
            filter((status: string) => status !== 'PENDING'),
            take(1)
          )
        ),
        filter((status: string) => status === 'VALID')
        )
        .subscribe(() => {
          return this.sendRequest();
        });
        ...
      }

      onSubmit() {
          this.formSubmitSubject$.next();
      }
      ....

When i submit the form i can wait for the completion of al the sync/async validators, and then if all the fields in form are valids, submit the form.

Now i need to create a method, inside this component like

    checkFormValidity(): boolean {
        // code
    }

that i can call from an other component, and wait for complete all sync/async validations using the formSubmitSubject$ and return the state of the form.

So, is possible to put the subject.pipe().subscribe() into a method and return the boolean value only when all is resolved?

Thanks in advance!

AngelPoyel
  • 160
  • 1
  • 9
  • Not sure, what is your question? Can you please rephrase. What I understood until now is, you want to figure out to apply async validation on field, and disable submit button until then.. Please correct me if I'm wrong – Pankaj Parkar Nov 24 '20 at 17:23
  • 1
    You can't return a boolean value from a function that's retrieving this value asynchronously. You should return an observable in your case `formIsValid(): Observable {}` – frido Nov 24 '20 at 17:27
  • I've edit the question to be more clearly – AngelPoyel Nov 24 '20 at 17:43
  • You can't call a components function from another component. You either need to use parent-child communication via `@Input` or `@Output` variables or use a Service that shares data with multiple components. You should probably put a `Subject` that's holding the formValidity boolean value in a Service. – frido Nov 24 '20 at 22:01
  • This should get you covered: https://stackoverflow.com/questions/34190375/how-can-i-await-on-an-rx-observable – TotallyNewb Nov 25 '20 at 09:02

0 Answers0