Will de la Vega
Will de la Vega

Reputation: 554

Is there an event to know when a form is valid?

I am using FormGroup, custom validators, etc. I need to capture in an event handler when the form becomes valid/invalid, not a property, but an actual event in TypeScript code.

I took a look to the documentation, but I wasn't able to find something like: (validityChange)="myEventHandler($event)"

where validityChange is just a placeholder for the name of the actual event I am looking for.

Upvotes: 13

Views: 14476

Answers (3)

rmcsharry
rmcsharry

Reputation: 5562

For Angular with RxJs 6+ (where you need to use pipe):

this.form.statusChanges
  .pipe(
    filter(() => this.form.valid))
  .subscribe(() => this.onFormValid());

this.form.valid is a property that is boolean and so will either be true or false. Hence the filter will return true when the form is valid and the subscribe will then only call this.onFormValid() when the property is true.

You can see what is going on by doing this:

  public ngOnInit() {
    this.form.statusChanges
      .pipe(
        filter((status: string) => {console.log(status); return this.form.valid}))
      .subscribe(() => this.onFormValid());
  }

  private onFormValid() {
    console.log('form is valid')
  }

One should also unsubscribe or take (complete), eg:

this.form.statusChanges
  .pipe(
    filter(() => this.form.valid)),
    takeUntil(this.destroy$)
  .subscribe(() => this.onFormValid());

ngOnDestroy() {
  this.destroy$.next();
}

Upvotes: 9

Alexander Abakumov
Alexander Abakumov

Reputation: 14549

Borrowing the idea from @Gunter's answer, but utilizing the current API you can simplify it and drop the usage of the 'VALID' constant from your code by using the valid property:

this.myForm.statusChanges
    .filter(() => this.myForm.valid)
    .subscribe(status: string => onValid());

By the way, depending on whether this subscription could lead to a memory leak, do not forget to unsubscribe() from it.

Upvotes: 3

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657546

Subscribe to statusChanges

this.myForm.statusChanges
.filter(s => s == 'VALID')
.subscribe(val => onValid())

Upvotes: 16

Related Questions