角度验证,必需不起作用

Gro*_*kku 10 typescript angular

最简单的例子永远不起作用.我使用Angular CLI v1.0.6生成了一个Angular 4应用程序,将app.component.html的内容更改为:

<form #form='ngForm' (ngSubmit)='submitForm(form.value)'>
  <input type='email'
  class='form-control' placeholder='E-mail' name='userEmail' ngModel required >
  <button type='submit'>Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

app.component.ts的内容为:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  submitForm(data){
    console.log(data);
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望在我没有提供电子邮件的情况下不会触发提交功能,但确实如此.我错过了什么?

PS:我已经四处寻找示例(例如:https://scotch.io/tutorials/angular-2-form-validation),但经过几个小时我无法找到解决方案,这就是我来找你的原因.我知道这是在我的脸上,但不知怎的,我看不到它.

Dal*_*vik 36

@Fredrik的回答是对的.

novalidate使用模板驱动方法时,Angular会自动将属性添加到表单中.这就是为什么你不能阻止提交.

但是,如果您想要浏览器验证ngNativeValidate,请在表单中添加属性.

  <form ngNativeValidate>
       <input type='text' name='projectName' [(ngModel)]='projectName' required >
       <input type='submit' value='submit' />
 <form>
Run Code Online (Sandbox Code Playgroud)

  • 你是个英雄,你知道这一点! (2认同)

ala*_*bid 12

上面的答案是对的,你只需要添加ngNativeValidate到表单标签中即可。我想补充一点,如果您希望提交按钮(click)在表单无效时不执行操作,请使用form.checkValidity()

<form ngNativeValidate #form >
   <input type="text" required/>
   <button name="submit"  type="submit" (click)="form.checkValidity()? login() : null">
          Sign In
   </button>
</form>
Run Code Online (Sandbox Code Playgroud)


Fre*_*din 9

novalidate使用模板驱动的方法时,Angular 会自动将属性添加到您的表单中。这就是为什么您不会被阻止提交的原因。

您可以使用form.valid查看整个表单是否有效,然后围绕您希望如何处理它创建自己的逻辑。