0

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: '',
    });
  }
2
  • 1
    If your data model and formcontrol keys are same you can use setValue on formGroup: this.modelForm.setValue(settings) Commented Sep 12, 2022 at 1:58
  • 1
    In your form builder, just set the corresponding property to the value you want, instead of '' Commented Sep 12, 2022 at 1:59

1 Answer 1

1

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])
})

Sign up to request clarification or add additional context in comments.

3 Comments

none of the answers work Sir , can you elaborate your solution 2?
the thing with your solution is that you are using key as a value so that means if you look at my setting object some of it has null values.
Okay. So it's simple. In 2nd way, you can setValue(Settings[key]). Let me update answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.