如何为自动保存的响应式Angular 2表单创建验证。

时间:2017-02-27 05:15:28

标签: angular ionic2 angular2-forms reactive-forms

我需要有关如何创建自动保存反应式Angular 2表单的建议。基本上用户输入值,如果验证了值,则表单自动保存。这是代码

    export class BusinessFoundationsPage {

      businessFoundationsForm: FormGroup;
      userId: string;
      YouTuber: YouTuber;
      loading: any;
      isThisFirstTimeFlag: boolean;
      businessFoundationsKey: string;
      locationId: string;

      constructor(public af: AngularFire, public navCtrl: NavController, public navParams: NavParams, public fb: FormBuilder, private loadingCtrl: LoadingController, public userData: UserData) {
        this.locationId = this.navParams.get('locationId');
        this.loading = this.loadingCtrl.create({
          content: 'Please wait...'
        });

        this.loading.present();

        this.businessFoundationsForm = this.fb.group({
          businessFoundationsQ1: ['', [Validators.required, Validators.minLength(10)]],
          businessFoundationsQ2: ['', [Validators.required, Validators.minLength(10)]]
        })

      }

      ionViewDidLoad() {
        console.log('ionViewDidLoad BusinessFoundationsPage');

        this.af.auth.subscribe(auth => {
          if (auth) {
            console.log ("Current State: Login");
            this.userId = auth.uid;
            this.userData.getUserDetail(this.userId).subscribe(user => {
              this.YouTuber = user;

              let formControls: any = this.businessFoundationsForm.controls;
              if (this.YouTuber.businessFoundations) {
                this.isThisFirstTimeFlag = false;
                this.userData.getBusinessFoundationsData(this.YouTuber.businessFoundations).subscribe(data => {
                  this.businessFoundationsKey = data.$key;
                  formControls.businessFoundationsQ1.setValue(data.businessFoundationsQ1);
                  formControls.businessFoundationsQ2.setValue(data.businessFoundationsQ2);
                  this.loading.dismiss();
                })
              } else {
                this.isThisFirstTimeFlag = true;
                this.loading.dismiss();
              }
            });

          } else {
            this.loading.dismiss();
            console.log ("Current State: NOT Login");
          }
        });

      }

      saveForm(): void {
        let data = this.businessFoundationsForm.value;
        let dataToSave = {
          locationId: this.locationId,
          uid: this.userId,
          youTuberName: this.YouTuber.name,
          businessFoundationsQ1: data.businessFoundationsQ1,
          businessFoundationsQ2: data.businessFoundationsQ2,
        }
        console.log (data);
        if (this.isThisFirstTimeFlag) {
          this.userData.createBusinessFoundationsData(this.userId, dataToSave);
        } else {
          this.userData.updateBusinessFoundationsData(this.businessFoundationsKey, dataToSave);
        }
      }

    }

3个输入字段包含Validators.required,Validators.minLength(10)。这是HTML:

    <form [formGroup]="businessFoundationsForm" (change)="saveForm()">
  <ion-item text-wrap>
    <ion-label floating>What additional revenue streams have the most growth potential for your channel?</ion-label>
    <ion-textarea fz-elastic formControlName="businessFoundationsQ1"></ion-textarea>
  </ion-item>
  <ion-item text-wrap>
    <ion-label floating>What is one business challenge you have and what can you do to improve in this area?</ion-label>
    <ion-textarea fz-elastic formControlName="businessFoundationsQ2"></ion-textarea>
  </ion-item>
</form>

每次通过点击我的firebase服务器更改输入时,都会保存表单。但我希望它仅在验证其中一个字段时保存。此外,如果字段值相同,我也不想调用Firebase(保存操作)。基本上,我需要在没有用户单击愚蠢的提交按钮的情况下最小化调用操作的数据库。我在Ionic 2 BTW。所以,让我们说情况可以是:

  1. 首先输入输入字段,但不符合验证 - saveForm stop。
  2. 输入字段首先输入,并且符合验证但第二个字段仍为空 - saveForm save(自动保存!!)
  3. 输入字段第二个是键入的,但不符合验证,字段首先不是更改 - saveForm stop。
  4. 输入字段第二个是键入的,并且符合验证,但字段首先是空的 - 仍然是saveForm save(AutoSave !!)
  5. 用户首先编辑字段但不符合验证,字段秒不变 - saveForm stop。
  6. 我想不出其他情况。关于如何用反应性/可观察的反应形式建立这个的任何建议?

1 个答案:

答案 0 :(得分:2)

订阅200 ms debounce或更多的值更改,因此如果用户未输入200 ms,则会调用subscribe。如果表单有效,请保存

constructor(public af: AngularFire, public navCtrl: NavController, public navParams: NavParams, public fb: FormBuilder, private loadingCtrl: LoadingController, public userData: UserData) {
    this.locationId = this.navParams.get('locationId');
    this.loading = this.loadingCtrl.create({
        content: 'Please wait...'
    });

    this.loading.present();

    this.businessFoundationsForm = this.fb.group({
        businessFoundationsQ1: ['', [Validators.required, Validators.minLength(10)]],
        businessFoundationsQ2: ['', [Validators.required, Validators.minLength(10)]]
    })

    this.businessFoundationsForm.valueChanges
        .debounceTime(200)
        .subscribe(() => {
            if (businessFoundationsForm.valid && businessFoundationsForm.dirty) {
                this.saveForm();
                businessFoundationsForm.reset()
            }
        });

}