Home > Enterprise >  FormGroup, get names of FormControl instead of numbers in Angular
FormGroup, get names of FormControl instead of numbers in Angular

Time:01-30

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 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

CodePudding user response:

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

  •  Tags:  
  • Related