Search code examples
angularangular-forms

Get projected form controls to participate in the form


If I have a form in a component that has an ng-content in the form can I get form controls that have been projected into the form to participate in the form?

<form #form="ngForm" (ngSubmit)="submit(form.form.valid)">
  <ng-content></ng-content>
  <button type="submit">Submit</button>
</form>

now if I use this component

<my-component>
  <input name="test" [(ngModel)]="test" required>
</my-component>

The form in the control is always valid as the projected form controls do not participate in the form. Is it possible to get the projected controls to participate in the form?

StackBlitz https://stackblitz.com/edit/angular-ivy-wc9ahr


Solution

  • Was hoping the easy way is just to add:

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

    But that doesn't work so seems like you'd have to add each control to ngForm

    @ContentChildren(NgModel) ngModels: QueryList<NgModel>;
    @ViewChild(NgForm) ngForm: NgForm;
    
    ngAfterViewInit(): void {
      this.ngModels.forEach((model) => {
        this.ngForm.addControl(model);
      });
    }
    

    https://stackblitz.com/edit/angular-ivy-johebo