Angular Form包装器

时间:2017-08-28 08:55:26

标签: angular

我目前正在处理表单的包装器。 Everthing在验证旁边工作。问题是我的ngForm属性不包含ng-content的控件。目标是ngSubmit EventEmitter仅在表单有效时才会发出。

这是当前状态:

import { Component, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
 selector: 'px-form',
 template: `
   <form (ngSubmit)="f.form.valid && ngSubmit.emit($event)" #f="ngForm">
     <ng-content></ng-content>
   </form>
})
export class PxFormComponent {
  @ViewChild('f') ngForm: NgForm;
  @Output() ngSubmit = new EventEmitter();
}

1 个答案:

答案 0 :(得分:0)

您可以在这篇文章中找到解决问题的方法:

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

从帖子中取得的代码:

@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);
  }
}