zer0
zer0

Reputation: 5017

How to add controls to a sub form in child component using FormGroupDirective?

I am trying to add controls to a formGroupName from a child component and subscribe to the changes on the formGroupName. This is what I have (please note that I am open to a better approach):

Parent/App Component HTML:

<form [formGroup]="mainForm">
  <p>Main</p>
  <input type="text" formControlName="mainInput" />
  <div formGroupName="childForm">
    <app-child></app-child>
  </div>
</form>

Parent/App Component TS:

export class AppComponent implements OnInit {
  mainForm: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.mainForm = this.fb.group({
      mainInput: [''],
      childForm: this.fb.group({
        childInput: [''],
      }),
    });

    this.mainForm
      .get('childForm')
      .valueChanges.subscribe((data) => console.log(data));
  }
}

Child Component HTML:

<div formGroupName="subSubForm">
  <p>Child</p>
  <input type="text" formControlName="childInput" />
</div>

Child Component TS:

export class ChildComponent implements OnInit {
  constructor(private fgd: FormGroupDirective, private fb: FormBuilder) {}

  ngOnInit() {
    let form = this.fb.group({
      selected: [false],
    });
    this.fgd.form.addControl('childTest', form);
  }
}

In the child component TS, what I want to be able to do is get the formgroupname and addcontrol to it. So this.fgd.form.get('childForm').addControl('childTest', form) but addControl does not exist on get.

StackBlitz

Upvotes: 0

Views: 1616

Answers (2)

Koi An
Koi An

Reputation: 70

You must add

providers: [
    { provide: ControlContainer, useExisting: FormGroupDirective },
] 

in child component.

Example: here

Upvotes: 2

Eliseo
Eliseo

Reputation: 57939

You can not use formGroupName without enclosed in a formGroup (see the errors in console).

So, declare a variable

subSubForm:FormGroup

Then, in ngOnInit use

  ngOnInit() {
    ...
    this.subSubForm=this.fgd.form.get('childForm') as FormGroup
    ...
  }

And in .html

<!--see that use [FormGroup] -->
<div [formGroup]="subSubForm">
  <p>Child</p>
  <input type="text" formControlName="childInput" />
</div>

Upvotes: 1

Related Questions