2

I'm trying to create nested reactive forms here : https://stackblitz.com/edit/angular-mgrfbj

This is the project heirarchy:

---create company form (hello.component.ts)
    --- company details form (company-details.component.ts)
    --- [
        employee details form (employee-details.component.ts)
        employee details form
        employee details form ...
        ]

For such nested forms, I have to use ViewProviders and FormGroupDirective as given in this video:

The first nested form (company-details.component.ts) is working as expected

But the second form which is added with *ngFor inside a FormArray is not binding to the FormGroupDirective correctly.

When you type the company details and press Print Json, then the printed json will be correct. But when you add an employee or two, then the employee details are not printed in the json.

I know there are other manual ways to accomplish the same thing, but I'm looking for a clean solution that just works without any extra functions.

Any help will be really appreciated!

Thanks in advance

2
  • did you notice that this.fgd is undefined in your employee-details ? Commented Dec 12, 2018 at 9:20
  • can you describe a little bit more about 'clean solution'? Commented Dec 12, 2018 at 9:25

1 Answer 1

3

there are to make several changes in your code

1.-The employed.details.component.html

<!---see that is [formGroup], not formGroupName-->
<div [formGroup]="employee">
  <h4 class="row">Employee no. {{index+1}}</h4>
  <div class='col-md-8'>
    <input formControlName="name" placeholder="Name">
  </div>
  <div class='col-md-8'>
    <input formControlName="planet" placeholder="Planet">
  </div>
</div>

2.- the employed.details.component.ts, becomes as

  employee: any;
  @Input() index;
  //inject the ForumGroupDirective in the variable fgd    
  constructor(private fb: FormBuilder,
              private fgd: FormGroupDirective) {}

  ngOnInit() {
    //get the FormArray of "employees"
    const array=(this.fgd.form.get('employees') as FormArray);

    //Simple push to the array
    array.push(this.fb.group({
      name: '',
      planet: ''
      }));
    //the formGroup must be array.at(index)
    this.employee = array.at(this.index)
  }

Finally, when remove the employe you must remove the element in the array

  removeEmployee() {
    this.employeesCount -= 1;
    (this.form.get('employees') as FormArray).removeAt(this.employeesCount);
  }

see the stackblitz

Sign up to request clarification or add additional context in comments.

1 Comment

Saved my day! Also got to know about the reactive forms in more depth! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.