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

FormGroup, get names of FormControl instead of numbers in Angular

I have in my code:

  private buildFormGroup() {
    const internalFormGroup = this.formBuilder.group({
      document: ['', [Validators.required, Validators.min(this.minValueDocument)]],
      company: ['', [Validators.required]],
      typeClient: ['', [Validators.required]],
      textRequest: ['', [Validators.required, Validators.minLength(this.minNumberCharPerRequest)]],
      files: [''],
      myKey: ['myValue'],
    });

    return internalFormGroup;
  }

In my constructor I have this lines following this answer:

this.formGroup = this.buildFormGroup();

for(let item in Object.keys(this.formGroup.controls)) {
  console.log(item)
}
for(let item in this.formGroup.controls) {
  console.log(this.formGroup.controls[item])
}

But, I get only numbers and the value appears empty!!!

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

enter image description here

I forget something? How I can get the name of the control (not the its Value)?

For my previous example: I would like to get: document, company, typeClient, textRequest,files, myKey

>Solution :

The for...in statement iterates over all enumerable properties of an object that are keyed by strings. MDN docs

Since you are already extracting the keys from controls into an array, the for…in is looping through the array keys.

You have to either use for...in directly on formGroup.controls.

for(let item in this.formGroup.controls) {
  console.log(item)
}

Or use for...of instead

for(let item of Object.keys(this.formGroup.controls)) {
  console.log(item)
}

cheers

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