【问题标题】:Get projected form controls to participate in the form获取投影表单控件以参与表单
【发布时间】:2021-02-19 10:51:58
【问题描述】:

如果我的组件中有一个表单,该表单中有一个 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

【问题讨论】:

    标签: angular angular-forms


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2020-04-22
      • 2020-04-25
      相关资源
      最近更新 更多