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

Time:05-05

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

CodePudding user response:

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>

CodePudding user response:

You must add

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

in child component.

Example: here

  • Related