angular 5 template forms detect change of form validity status

后端 未结 3 957
说谎
说谎 2020-12-13 14:11

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 method

相关标签:
3条回答
  • 2020-12-13 14:31

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-13 14:42

    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

    0 讨论(0)
  • 2020-12-13 14:53

    You can subscribe to the whole form changes and implement your logic there.

    @ViewChild('myForm') myForm;
    
    this.myForm.valueChanges.subscribe(data => console.log('Form changes', data));
    
    0 讨论(0)
提交回复
热议问题