简体   繁体   English

按钮验证-Angular 2反应形式

[英]Button validation - Angular 2 Reactive forms

I have used reactive forms in my angular 2 project. 我在我的angular 2项目中使用了反应形式。 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. 在我的表单中,有两种输入方法。 ie 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 示例示例: https//stackblitz.com/edit/angular-vnqqcx

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 或创建一个customValidator并检查该组是否有效

  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 stackblitz

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. 这就是Form valid/invalid属性的用途。 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 https://stackblitz.com/edit/angular-cdfj8z?file=src/app/app.component.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM