0
votes

I'm trying to create a ReactiveForm in Angular with this data heirarchy:

-company
  -name
  -city
-employee1
  -name
  -planet
-employee2
  -name
  -planet

I have created a component CompanyDetailsComponent and another EmployeeDetailsComponent

I want to reuse the EmployeeDetailsComponent with formGroupNames employee1 & employee2

Here's the code stackblitz

Actually I want to make it work for a variable number of employees I have to keep the structure flat(I can't use an array of employees, in which case I would have used the FormArray like this)

So to achieve this flat heirarchy structure I was trying to do it for 2 employees first.

Any help would be greatly appreciated

Thank you in advance!

3

3 Answers

2
votes

There are several steps to make it working:

Change form template as follows:

<form [formGroup]="form">
  <app-company-details></app-company-details>
  <app-employee-details jsonname="employee1"></app-employee-details>
  <app-employee-details jsonname="employee2"></app-employee-details>
</form>

Create nested form group based on provided jsonname string:

employee-details.component.ts

@Component({
  selector: 'app-employee-details',
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ],
  ...
})
export class EmployeeDetailsComponent implements OnInit {
  @Input() jsonname;

  constructor(private fb: FormBuilder, private fgd: FormGroupDirective) { }

  ngOnInit() {
    const group = this.fb.group({
      name: new FormControl(),
      planet: new FormControl()
    });

    this.fgd.form.addControl(this.jsonname, group);
  }
}

employee-details.component.html

<div [formGroupName]="jsonname">
  ...
</div>

Stackblitz Example

1
votes

I think you've since edited it with yurzui's suggestion, but I took a look and fixed a small bug that was preventing it from working and here's the link:

Stackblitz

You had square brackets around attributes that weren't pulling their values from the component. For example, I changed [jsonname]="employee2" to jsonname="employee2".

Hopefully it is working as intended now.

0
votes

Issue since angular 9 not allowing number as formGroupName. This is due to strict type checking in angular.Below solution worked for me.

Non Working Code:

<ng-container *ngFor="let configurationCtrl of configurationForm.get('configurations').value;
let i = index" [formGroupName]="i">

Working Code:

<ng-container *ngFor="let configurationCtrl of configurationForm.get('configurations')['controls'];
let i = index" [formGroupName]="i">

Note : I replaced value with controls.