【问题标题】:Angular2 ngNoForm and also do angular form validationAngular2 ngNoForm 并且还进行角度表单验证
【发布时间】:2017-02-07 22:26:01
【问题描述】:

我有一个将表单数据作为请求参数处理的旧式后端服务器。 我们将 angular2 放在前端。我想提交 angular2 表单,以便所有字段都作为请求参数,这样就不必更改遗留后端。 为此,我有:

<form  ngNoForm action="http://localhost/config/api/v1/angular/submit" target="_blank" method="POST">

但我也想在提交按钮上使用 angular2 表单验证:

<form #f="ngForm" ngNoForm action="http://localhost/config/api/v1/angular/submit" target="_blank" method="POST">
 <button type="submit" [disabled]="!f.form.valid" class="small round">Submit</button>

但这不起作用 - angular2 在声明 ngNoForm 时抱怨有 #f="ngForm"。

有什么方法可以像往常一样进行 angular2 表单验证,并将表单作为常规请求参数提交?

【问题讨论】:

  • 我正在使用 ReactiveForms 和 AJAX 请求来实现这一点。我没有使用ngNoForm 的经验。我将请求参数添加到字符串数组中,像arr.join('&amp;') 一样加入它们,然后使用encodeURI(body) 对其进行编码。肯定不止于此,但这是组织表单数据的要点。在你的 TS 中。如果您可以使用旧版应用程序执行此操作,我可以发布更详细的答案。
  • 不幸的是,由于整个表单是元数据驱动的,我不知道页面上有哪些字段。我想我可以使用 javascript 找出页面上的哪些字段,然后实现你提到的解决方案。谢谢。

标签: angular angular2-forms


【解决方案1】:

使用纯 JS 强制提交,这对我有用:

<form ngNoForm [formGroup]="myForm" action="http://test.local/process_post.php" target="_blank" method="POST">
    <input formControlName="alpha" name="alpha"/>
    <input formControlName="beta" name="beta"/>
    <button type="submit" [disabled]="!myForm.valid" onclick="submit()">SEND</button>
</form>

【讨论】:

  • 我不想使用 formGroup,即我想使用 [ngModel] 绑定方式,因为我的表单基于服务器发送的数据非常动态,并且只有模板驱动的表单,即使用ngModel 非常适合我们。
  • 是否可以使用表单标签外的按钮通过ngNoForm提交
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 2019-04-25
  • 1970-01-01
  • 2016-01-14
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多