离子2 - 设定模型驱动形式的值

时间:2016-12-14 11:07:18

标签: angular local-storage ionic2 angular2-forms

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

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

  

TypeError:设置只有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');
    });

  }
}

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

2 个答案:

答案 0 :(得分:8)

public static void SelectOptions(String value) { driver.findElement(By.xpath("//input[@value='"+value+"']")).click(); } 的属性FormGroup是一个只读属性,这意味着您无法直接编辑它。您需要使用value函数获取每个get(),然后使用FormControl函数更改其值。无论如何,而不是:

setValue()

你需要使用它:

this.form.value = data;

答案 1 :(得分:0)

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

// localstorage 
this.storage = storage;