我正在尝试在angular 8中应用验证,但无法正常工作

时间:2020-02-13 12:27:29

标签: angular typescript

<form> 
  <input type="email" [(ngModel)]="credentials.email" #email="ngModel" name="email" ngModel required>
  <input type="password" [(ngModel)]="credentials.password" #password="ngModel" name="password" ngModel required>
  <button type="button" (click)="login()">Sign in</button>
</form>

如果我单击登录按钮后没有任何输入,则必填字段不起作用...我已经尝试以另一种方式解决此问题,但是它不起作用。 我如何申请验证器?

3 个答案:

答案 0 :(得分:0)

似乎您混合了反应形式和模板驱动的模式。坚持一种方法,并以各自的方式来做。

反应式:https://angular.io/guide/reactive-forms 模板驱动:https://angular.io/guide/forms 验证:https://angular.io/guide/form-validation

答案 1 :(得分:0)

使用反应形式尝试。

请参考-> https://angular.io/guide/reactive-forms

component.html文件。

<form [formGroup]="loginform"> 
  <input type="email" formControlName="email" ngModel required>
  <input type="password" formControlName="password" ngModel required>
  <button type="button" (click)="login()">Sign in</button>
</form>

添加验证 component.ts文件。

loginform: FormGroup;

ngOnInit{

this.loginform = this.fb.group({
      email: ['', [Validators.required]],
      password: ['', [Validators.required, Validators.minLength(7)]],
  });
}

答案 2 :(得分:0)

请在表单中添加ngForm

<form (ngSubmit)="login()" #heroForm="ngForm"> 
 <input type="email" [(ngModel)]="credentials.email" #email="ngModel" name="email" ngModel required>
 <input type="password" [(ngModel)]="credentials.password" #password="ngModel" name="password" ngModel required>
 <button type="submit" [disabled]="!heroForm.form.valid" (click)="login()">Sign in</button>
</form>