Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 template forms detect change of form validity status

are reactive forms the way to go in order to have a component that can listen for changes in the validity status of the form it contains and execute some compoment's methods?

It is easy to disable the submit button in the template using templateRef like [disabled]="#myForm.invalid", but this does not involve the component's logic.

Looking at template forms' doc I did not find a way

like image 730
Cec Avatar asked Apr 05 '18 06:04

Cec


People also ask

How does Angular determine changes in form?

In Angular we have observables which subscribe to form value changes. what you have to do is, subscribe to the form instance and detect any changes to the form. Suppose you don't want to include save button on your form. whenever user change any thing in the form save data to the server.

How do I validate a template driven form?

To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.

How do you set a validator dynamically?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.


2 Answers

If you want to get only the status and not the value you can use statusChanges:

export class Component {      @ViewChild('myForm') myForm;      this.myForm.statusChanges.subscribe(         result => console.log(result)     ); } 

If you even want data changes, you can subscribe to the valueChanges of the form and check the status of the form using this.myForm.status:

export class Component {      @ViewChild('myForm') myForm;      this.myForm.valueChanges.subscribe(         result => console.log(this.myForm.status)     ); } 

Possible values of status are: VALID, INVALID, PENDING, or DISABLED.

Here is the reference for the same

like image 155
Sravan Avatar answered Oct 21 '22 11:10

Sravan


You can do something like this do detect a validity change and execute a method based on whether the form is VALID or INVALID.

this.myForm.statusChanges   .subscribe(val => this.onFormValidation(val));  onFormValidation(validity: string) {   switch (validity) {     case "VALID":       // do 'form valid' action       break;     case "INVALID":       // do 'form invalid' action       break;   } } 
like image 33
Chris Halcrow Avatar answered Oct 21 '22 09:10

Chris Halcrow