Thodoris
Thodoris

Reputation: 742

Angular - Find type of form groups controls

I have the following reactive form. What I want to do is to make a copy of a part of the form and turn it into a new one.

 this.myForm = this.formBuilder.group({
            group: this.formBuilder.group({
                name: 'Zero',
                lastName: 'Zeroo'
            }),
            name: 'One',
            array: this.formBuilder.array([
                { name: 'two'},
                { name: 'three'}
                ])
        });

With the following code, I try to do the copy.

    let formControlKeys = Object.keys(this.myForm.value);
    this.myCopyForm = this.formBuilder.group({});
    for (let key of formControlKeys){
              console.log(typeof this.myForm.controls[key]);
              // prints object

              // code to create new FormControl / FormGroup / FormArray 
              // inside myCopyForm according to type got above
          }

The required functionality is to get the reactive-form type and not only object.

Upvotes: 0

Views: 9073

Answers (1)

vince
vince

Reputation: 8306

You're on the right track. The catch here is that when you try to console.log the type of something using the typeof keyword, you are actually getting the run-time Javascript type of that thing, which in this case is an object. Typescript is a compile-to-JS language, meaning that all those fancy types and interfaces and such are only used for static type checking. When the your code gets to the browser, all of that type information is gone and you're looking and plain old Javascript.

So, the type of this.myForm.controls[key] at the point you're referencing it in the code actually is what you want, an AbstractControl. You can use those controls to build a copy of your form, like so:

this.copyForm = new FormGroup({});
for (let key of Object.keys(this.myForm.value)) {
  const control = this.myForm.controls[key]; // AbstractControl
  this.copyForm.addControl(key, control);
}

More information on the FormGroup API can be found here: https://angular.io/api/forms/FormGroup.

Upvotes: 1

Related Questions