angularformsangular-reactive-formsangular-forms

How to reorder items in FormGroup?


I have element in a FormGroup, let say

const langs = ['en', 'de']
form = new FormGroup({
  languages: [langs, [Validators.required]]
  descriptions: initChildGroup(langs)
})

initChildGroup(langs) {
  const formGroup: FormGroup = new FormGroup({})

  langs.forEach((lang, index) => {
    formGroup.addControl(lang, new FormControl())
  }  
}

I now want to move the order of the lang and put 'de' first.
Moving element in an array is quite an easy task, but how to handle this properly with a FormGroup ?


Solution

  • The order of the controls in a FormGroup do not matter. They are similar to the JavaScript object data structure, the order of the keys do not matter.

    When you work with FormArray the order matters, similar to the JavaScript array data structure.

    So just reorder your HTML any way you like and the form group will work fine, without touching the FormGroup data structure.