Assign formgroup inside a typed form group

53 Views Asked by At

With the introduction of typed forms in angular 14, The following forms are typed.

I have a component where the formgroup group1 is initialized as follows:

this.form = this.formBuilder.group({
   someProp: this.formBuilder.control(""),
   group2: (this.someCondtion ? this.alreadyInitialiedForm : this.formBuilder.group({}))
})

Now, After sometime, I patch the form value with this.alreadyInitializedForm after someCondition is true(In the above code the consider the someCondition to be false).

this.form.patchValue({
   group2: this.alreadyInitialiedForm.value
})

The value gets updated but the group2 formGroup does not have controls in it.They are empty.

How can I handle this case? I tried initializing the this.form with all the properties in group2 form like this:

this.form = this.formBuilder.group({
   someProp: this.formBuilder.control(""),
   group2: (this.someCondtion ? 
      this.alreadyInitialiedForm : 
        this.formBuilder.group({
           someProp1: this.formbuilder.control(""),
           // and so on
        }))
})

But in my case,There are so many properties.So i am trying to find a better way.

1

There are 1 best solutions below

0
On

This might help you keep your code cleaner and avoid duplicating properties:

form: FormGroup;

constructor(private formBuilder: FormBuilder) { }

ngOnInit(): void {
  this.form = this.formBuilder.group({
    someProp: this.formBuilder.control(""),     
    group2: this.buildGroup2()
  });

    // Later, when someCondition becomes true, you can patch the form value
    // with the alreadyInitializedForm's value
  if (someCondition) {
    this.form.patchValue({
      group2: this.alreadyInitializedForm.value
    });
  }
}

private buildGroup2(): FormGroup {
  if (someCondition) {
    return this.alreadyInitializedForm;
  } else {
    return this.formBuilder.group({
      someProp1: this.formBuilder.control(""),
      // Add other properties as needed
    });
  }
}