How to observe touched event on Angular 2 NgForm?

后端 未结 4 1855
青春惊慌失措
青春惊慌失措 2020-12-18 18:53

It is possible to subscribe a callback to an NgForm\'s valueChanges observable property in order to react to changes in the values of the controls

4条回答
  •  温柔的废话
    2020-12-18 19:37

    You can extend default FormControl class, and add markAsTouched method that will call native method, plus your side effect.

    import { Injectable } from '@angular/core';
    import { FormControl, AsyncValidatorFn, ValidatorFn } from '@angular/forms';
    import { Subscription, Subject, Observable } from 'rxjs';
    
    export class ExtendedFormControl extends FormControl {
      statusChanges$: Subscription;
      touchedChanges: Subject = new Subject();
    
      constructor(
        formState: Object,
        validator: ValidatorFn | ValidatorFn[] = null,
        asyncValidator: AsyncValidatorFn | AsyncValidatorFn[] = null
      ) {
        super(formState, validator, asyncValidator);
    
        this.statusChanges$ = Observable.merge(
          this.valueChanges,
          this.touchedChanges.distinctUntilChanged()
        ).subscribe(() => {
          console.log('new value or field was touched');
        });
      }
    
      markAsTouched({ onlySelf }: { onlySelf?: boolean } = {}): void {
        super.markAsTouched({ onlySelf });
    
        this.touchedChanges.next(true);
      }
    }
    

提交回复
热议问题