Angular2 Forms - submit button disabled?

If the submit button is disabled until the form is valid? Best practice

Does angular2 have the equivalent of ng-disabled that you can use when you click the submit button? (ng-disabled does not work for me.)

+113
angular forms
Aug 18 '15 at 1:09 on
source share
4 answers

see example here, in Angular 2, this is a way to disable the button until the whole form is valid:

<button type="submit" [disabled]="!ngForm.valid">Submit</button> 
+210
Aug 18 '15 at 20:53 on
source share

in Angular 2.xx , 4 , 5 ...

 <form #loginForm="ngForm"> <input type="text" required> <button type="submit" [disabled]="loginForm.form.invalid">Submit</button> </form> 
+43
Mar 16 '17 at 14:28
source share

Here is a working example (you need to trust me that the controller has a submit () method - it prints an object, for example {user: 'abc'}, if "abc" is entered in the input field):

 <form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)"> <input type="text" name="user" ngModel required> <button type="submit" [disabled]="loginForm.invalid"> Submit </button> </form> 

As you can see:

  • don't use loginForm.form, just use loginForm
  • loginForm.invalid works just like! loginForm.valid
  • If you want submit () to pass the correct values, the input element must have ngModel name and attributes

Also, this is when you are NOT using the new FormBuilder, which I recommend. When using FormBuilder, everything is very different.

+2
Jul 07 '17 at 2:16 on
source share

Form validation is very simple in Angular 2

Here is an example

 <form (ngSubmit)="onSubmit()" #myForm="ngForm"> <div class="form-group"> <label for="firstname">First Name</label> <input type="text" class="form-control" id="firstname" required [(ngModel)]="firstname" name="firstname"> </div> <div class="form-group"> <label for="middlename">Middle Name</label> <input type="text" class="form-control" id="middlename" [(ngModel)]="middlename" name="middlename"> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input type="text" class="form-control" id="lastname" required minlength = '2' maxlength="6" [(ngModel)] = "lastname" name="lastname"> </div> <div class="form-group"> <label for="mobnumber">Mob Number</label> <input type="text" class="form-control" id="mobnumber" minlength = '2' maxlength="10" pattern="^[0-9()\-+\s]+$" [(ngModel)] = "mobnumber" name="mobnumber"> </div> <button type="submit" [disabled]="!myForm.form.valid">Submit</button> </form> 

Check out this plunker for a demo.

Additional Information

+2
Oct 11 '17 at 5:53 on
source share



All Articles