How to make 'submit' button disabled?
How to disable the "Submit" button until the form is valid?
Does angular2 have an equivalent to ng-disabled that can be used on the Submit button? (ng-disabled doesn't work for me.)
Solution 1:
As seen in this Angular example, there is a way to disable a button until the whole form is valid:
<button type="submit" [disabled]="!ngForm.valid">Submit</button>
Solution 2:
in Angular 2.x.x , 4, 5 ...
<form #loginForm="ngForm">
<input type="text" required>
<button type="submit" [disabled]="loginForm.form.invalid">Submit</button>
</form>
Solution 3:
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
Solution 4:
Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {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 as well as !loginForm.valid
- if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes
Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.