angular - Q : How to use Angular 2 template form with ng-content?

标签 angular angular2-forms

难道不可能在 ng-content 中包含表单输入元素并将其“连接”到父组件的 ngForm 实例吗?

将这个基本模板作为父组件:

<form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate>               
<ng-content></ng-content>
<button type="submit">Submit</button>
</form>

然后在“ng-content”中的子组件中,像这样:

<input type="text" [(ngModel)]="user.firstName" #firstName="ngModel" name="firstName" required minlength="2">

在提交父表单时,子控件不可用,这也意味着子组件中的脏/验证不会反射(reflect)在父表单上。

这里缺少什么?

最佳答案

此时您很有可能想出了另一个解决方案,但我只是想出了一个方法来做到这一点。希望它能对您或其他人有所帮助。

import { NgModel } from '@angular/forms';
import { Component, ContentChildren, ViewChild, QueryList, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-custom-form',
  template: `
    <form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate>               
      <ng-content></ng-content>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class MyCustomFormComponent implements AfterViewInit {
  @ContentChildren(NgModel) public models: QueryList<NgModel>;
  @ViewChild(NgForm) public form: NgForm;

  public ngAfterViewInit(): void {
    let ngContentModels = this.models.toArray();
    ngContentModels.forEach((model) => {
      this.form.addControl(model);
    });
  }

  public onSubmit(editForm: any): void {
    console.log(editForm);
  }
}

然后你可以像这样在你的模板中使用它:

<my-custom-form>
  <input name="projectedInput" ngModel>
</my-custom-form>

提交表单时,您会看到 projectedInput 表单控件已添加到 NgForm。

注意:我只尝试添加来自 AfterViewInit 生命周期 Hook 的预计输入。它可能会更早工作,我不确定。这样做也可能存在一些我不知道的问题。 YMMV.

关于angular - Q : How to use Angular 2 template form with ng-content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40843307/

相关文章:

javascript - Angular2 路由中的问题。子级的输入未呈现

angular - NativeScript ScrollView 当组件打开时它会滚动到某个部分

html - 使用 Angular2 单击更改图像

Angular 2 - 表单组组件

angular - 当表单模型中的值更新时,如何强制 Angular 2 更改检测?

将 TranslateService 注入(inject)拦截器时的 Angular 循环依赖

angular - 与应用程序组件中的包进行通信的正确方法是什么?

angular - 双向绑定(bind) - 嵌套对象 - Angular - 无法读取未定义的属性

typescript - Angular2 测试版 : nesting form-based parent/child components and validating from parent

Angular 2 : ngModel not working when wrapped with an ngIf directive