当我每次加载此文件时都想将以前从本地存储中保存的值归因于该表单时,我会陷入与Ionic 2内置的模型驱动表单相关的问题。

我设法使用Ionic的存储服务将其保存,但是我无法将已保存的数据归因于表单。我收到以下错误:



到目前为止,这是我的代码:

import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-survey',
  templateUrl: 'survey.html',
  providers: [Storage]
})

export class Survey {
  form: FormGroup;
  networkStatus: boolean = true;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public formBuilder: FormBuilder, private storage: Storage) {

    // localstorage
    this.storage = storage;

    this.form = formBuilder.group({
      "isPropertyOwner": ["", Validators.required],
      "familyMembers": ["", Validators.compose([Validators.required, Validators.minLength(0)])],
      "ownsProperty": ["", Validators.required],
      "pragueIdentify": ["", Validators.required],
      "pesticidesUsage": ["", Validators.required],
      "propertyLevel": ["", Validators.required]
    });

    /* Check if form has been changed */
   this.form.valueChanges.subscribe(data =>
      this.storage.set('survey', data)
    );
  }

  ngAfterViewInit() {
    // checking if there's something saved, then...
    if(this.storage.get('survey')) {
      this.storage.get('survey').then((data) => {
        console.log('This is ', data);
        this.form.value = data;
      });
    }
  }

  onSubmit(form) {
    console.log(form);
    this.storage.clear().then(() => {
      console.log('Keys have been cleared');
    });

  }
}

如何将保存的值归因于此表单?

最佳答案

FormGroup的属性value是只读属性,表示您不能直接对其进行编辑。您需要使用get()函数来获取每个FormControl,然后使用setValue()函数来更改其值。无论如何,代替这个:

this.form.value = data;

您需要使用此:
this.form.get('isPropertyOwner').setValue(data.isPropertyOwner);
this.form.get('familyMembers').setValue(data.familyMembers);
this.form.get('ownsProperty').setValue(data.ownsProperty);
this.form.get('pragueIdentify').setValue(data.pragueIdentify);
this.form.get('pesticidesUsage').setValue(data.pesticidesUsage);
this.form.get('propertyLevel').setValue(data.propertyLevel);

关于angular - ionic 2-模型驱动表格的设置值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41141071/

10-12 17:12
查看更多