Ionic 2 - 模型驱动形式的设置值

Ionic 2 - Setting value of a model driven form

当我想在加载此表单时将以前保存的值从本地存储归因于此表单时,我遇到了与 Ionic 2 中内置的模型驱动表单相关的问题。

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

TypeError: setting a property that has only a getter

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

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');
    });

  }
}

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

我认为您必须在从 constructor 中删除以下两行后进行检查,因为您已经将 private storage: Storage 声明为 constructor 参数。

// localstorage 
this.storage = storage;

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);