Reputation: 193
I'm stuck with something related to a model driven form, built in Ionic 2, when I want to attribute previously saved values from a local storage to this form whenever I load this.
I managed to save it using the Storage service from Ionic, however I failed on attributing this saved data to the form. I get the following error:
TypeError: setting a property that has only a getter
This is my code, so far:
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');
});
}
}
How could I attribute saved values to this form?
Upvotes: 2
Views: 4344
Reputation: 50633
FormGroup
's property value
is a read-only property which means you can't edit it directly. You need to use get()
function to get each FormControl
and then use setValue()
function to change its value. Anyway, instead of this:
this.form.value = data;
You need to use this:
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);
Upvotes: 10
Reputation: 13558
I think you have to check after removing below two lines from your constructor
as you have already declared private storage: Storage
as constructor
params.
// localstorage
this.storage = storage;
Upvotes: 0