获取投影表单控件以参与表单

Get projected form controls to participate in the form

如果我在组件中有一个表单,在表单中有一个 ng-content,我可以获取已经投影到表单中的表单控件来参与表单吗?

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

现在如果我使用这个组件

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

控件中的窗体始终有效,因为投影窗体控件不参与窗体。能否让投影控件参与到表单中?

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

希望简单的方法就是添加:

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

但这不起作用,所以您似乎必须将每个控件添加到 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