Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dynamic angular form builder according to array

i have array and want to set formControl from it.

How to create dynamic formControl?

const myArr = [ { "name": [ "Ivan" ] }, { "surname": [ "avan" ] } ]
form!: FormGroup;

constructor(private fb: FormBuilder){
this.form = this.fb.group(
  this.e.map(i => {
    return { [i.name]: [i.surname] }
  }));
}

This code return undefined form, so how to solve it? thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to use a FormArray. However, your data looks a bit off to me. I’m assuming you have an array of objects as such:

  [
    {
      "name": "Ivan",
      "surname": "Avan"
    },
    ...
  ]

Making your component:

export YourComponent implements OnInit {

  data: { name: string, surname: string } = [{
      name: 'Ivan',
      surname: 'Avan',
    }];
  form: FormArray;

  ngOnInit(): void {
    this.form = new FormArray(this.data.map(obj => {
        return new FormGroup({
          name: new FormControl(obj.name),
          surname: new FormControl(obj.surname),
        });
      }) || []);
  }

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading