Home > OS >  assigning FormGroup object values in angular
assigning FormGroup object values in angular

Time:09-12

I wanted to assign every key value from settings data to my modelForm , currently I do this one by one like this.modelForm.get('NotStarted').setValue(settings.NotStarted) , now I dont wanna do it one by one , is there a way we can directly assign all settings values to the modelForm object?

Thanks for any help and idea , appreaciated.

#objectToAssign

  settings =  {
        "Draft": "",
        "NotStarted": "NotStarted",
        "Submitted": "",
        "InPeerReview": "",
        "Accepted": "",
        "Migrated": ""
    }

#ts snippet code

 modelForm: FormGroup;
  this.modelForm = this.setFormGroup();
  setFormGroup(): FormGroup {
    return this.formBuilder.group({
      Draft: '',
      NotStarted: '',
      Submitted: '',
      InPeerReview: '',
      Accepted: '',
      Migrated: '',
    });
  }

CodePudding user response:

UPDATED

Instead of mapping the normal object. you can directly setValue to the modelForm.
Like below

let o = {
  Draft: '',
  NotStarted: '',
  Submitted: '',
  InPeerReview: '',
  Accepted: '',
  Migrated: '',
};

Object.keys(o).forEach(key => {
  this.modelForm.get(key).setValue(o[key])
})

  • Related