本文介绍了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

例如.以编程方式提交,或使用 标签之外的 提交.

eg. Either submit it programatically, or with a <button type="submit"> that is outside the <form> tags.

推荐答案

找到方法:

  • 使用 .ngSubmit.emit()
  • 触发提交
  • 使用 .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

这篇关于Angular2 - 从外部验证和提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:07