Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe touched event on Angular 2 NgForm?

Tags:

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 of the form.

I need, in the same fashion, to react to the event of the user touching one of the form controls.

This class seem to define the valueChanges Observable and the touched property is defined as a boolean.

Is there a way to to react to the "control touched" event?

like image 818
Chedy2149 Avatar asked Dec 26 '16 22:12

Chedy2149


People also ask

How do I know if my NgForm is valid?

You can check if firstNameForm. valid is false and then iterate the control groups and controls for errors. The NgForm class has the errors property because it inherits from AbstractControlDirective but the errors from nested controls are not collected there.

What is reactive forms in angular?

Reactive forms include a set of validator functions for common use cases. These functions receive a control to validate against and return an error object or a null value based on the validation check. Import the Validators class from the @angular/forms package.


1 Answers

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<boolean> = new Subject<boolean>();    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);   } } 
like image 86
Eggy Avatar answered Oct 03 '22 21:10

Eggy