0
votes

I have used reactive forms in my angular 2 project. I'm trying to do button validation but facing bit confuse. Here my form contains several text fields and buttons. In my form there are two way's to give input. i.e through input textfields and upload spread sheet button.

If we try to give input from text fields, my upload button should disable and If remove data from textfields upload button should enable. How to achieve this functionality.

Sample example: https://stackblitz.com/edit/angular-vnqqcx

2
stackblitz would be great.Antoniossss
you should better use !SignupForm.valid to disable your submit buttonMehdi Benmoha
@MehdiBenmoha Yeah I've tried already which you suggested, but I don't think so this will work for this particular scenario.Jayden

2 Answers

1
votes

You can subscribe to

empty=true;
this.SignupForm.controls.userData.valueChanges.subscribe(res=>{
      this.empty=!res.username && !res.email
    })

Or create a customValidator and check is the group es valid

  this.SignupForm = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null),
        'email': new FormControl(null),
      }, this.userDataValidator())
    });
  userDataValidator() {
    return (group: FormGroup) => {
      return (!group.value.username && !group.value.email) ? null : 
         { error: 'filled' }
    }
  }

or use a getter

  get isEmpty()
  {
    return !this.SignupForm || !this.SignupForm.controls.userData
           || (!this.SignupForm.controls.userData.value.username &&
               !this.SignupForm.controls.userData.value.email)
  }

see stackblitz

0
votes

what you want do do is to allow user to submit the form it it is valid. That is what valid/invalid properties of Form are for. So instead

<button class="btn btn-primary" type="submit" [disabled]="SignupForm.dirty" >Submit</button>  

use

    <button class="btn btn-primary" type="submit" [disabled]="SignupForm.invalid" >Submit</button> 

It works well with data validation.

https://stackblitz.com/edit/angular-cdfj8z?file=src/app/app.component.html