angular2 validate form on button click

2019-04-05 09:03发布

If I submit a form using button type="submit" the form validation messages appear and everything is fine. However if I have a button (or link) with (click)="myhandler()" then the validations do not appear.

How can I either:

  • tag the element as requiring validators to run, or
  • programatically run and show validation messages.

Note: These are simple validations like required on input fields.

Sample Code:

<form (ngSubmit)="save()">                       
  <input required type='text' [(ngModel)]="name">
  <!-- Shows validation messages but still calls save() -->
  <button (click)="save()">Click</button>  
  <!-- Only submits if valid and shows messages -->       
  <button type="submit">Submit</button>         
</form>
<!-- does not even show validation messages, just calls save -->
<button (click)="save()">Click 2</button>  

7条回答
beautiful°
2楼-- · 2019-04-05 10:09

Button with type submit triggers form submit automatically, i guess you have to trigger form submit manually:

<form (ngSubmit)="save()" #form="ngForm">

<button (click)="form.onSubmit()">Click 2</button> 

Why "ngForm"? A directive's exportAs property tells Angular how to link local variable to the directive. We set name to ngForm because the NgControlName directive's exportAs property happens to be "ngForm".

documentation

查看更多
登录 后发表回答