Angular2-从外部验证并提交表单
问题描述:
我有一个简单的表格,看起来像这样
I have a simple form that looks like this
<form (ngSubmit)="save()" #documentEditForm="ngForm">
...
</form>
,并且需要提交表单并从外部
and need to submit the the form and check its validity from outside
例如可以通过编程方式提交,也可以使用<form>
标记之外的<button type="submit">
提交.
eg. Either submit it programatically, or with a <button type="submit">
that is outside the <form>
tags.
答
了解如何操作:
- 触发使用
<formname>.ngSubmit.emit()
提交
- 通过
<formname>.form.valid
获取表单状态
- trigger submit with
<formname>.ngSubmit.emit()
- get form status with
<formname>.form.valid
示例:
<form (ngSubmit)="save()" #documentEditForm="ngForm">
...
</form>
<button class="btn-save button primary"
(click)="documentEditForm.ngSubmit.emit()"
[disabled]="!documentEditForm.form.valid">SAVE</button>
正如@ yuriy-yakovenko指出的那样,您应该在组件代码中添加以下内容:
As @yuriy-yakovenko has pointed out, you should add in your component code the following:
@ViewChild('documentEditForm') documentEditForm: FormGroupDirective;
如果您还没有完成导入,请不要忘记导入FormGroupDirective
And don't forget to import the FormGroupDirective
if you haven't done yet