角度表单包装器

  • 本文关键字:包装 表单 angular
  • 更新时间 :
  • 英文 :


我目前正在为表单制作包装器。一切都在验证旁边工作。问题是我的 ngForm 属性不包含来自 ng 内容的控件。目标是 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();
}

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

问:如何使用带有ng内容的Angular 2模板表单?

代码取自帖子:

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

最新更新