How to disable submit button until form is valid in angular 12?

Viewed 446

login.component.html

<form (ngSubmit)="submitLogin()" #loginForm="ngForm">

<div class="form-group">
  <label for="exampleInputEmail1">Email address</label>
  <input type="email" class="form-control" id="email" name="email" [(ngModel)]="form.email" [ngModelOptions]="{standalone: true}" required>
</div>

<div class="form-group">
  <label for="exampleInputPassword1">Password</label>
  <input type="password" class="form-control" id="password" name="password" [(ngModel)]="form.password" [ngModelOptions]="{standalone: true}" required>
</div>

<button type="submit" class="btn btn-primary" [disabled]="!loginForm.form.valid">Submit</button>

</form>

I am new in angular and I trying to disabled submit button until form input field is blank but here it showing enable but if I code like "loginForm.form.valid" then the submit button show disabled after put ! like "!loginForm.form.valid" then again it show enable submit button. So, How can I fix this issue? Please help me.

Thank You

4 Answers

Method 1:

Try [disabled]="!loginForm.valid" dont use form key word.

And add disabled css like below.

button:disabled{
  cursor:not-allowed;
  opacity:0.5
}

Method 2

Use get method in component

get form():FormGroup{
  return this.loginForm
}

In HTML use [disabled]="!form.valid"

You can bind it to a function to make it update itself.

Template:

[disabled]="invalidForm()"

Ts:

public invalidForm() {
  return !loginForm.form.valid;
}

Try this if the other answers don't work.

<button type="submit" class="btn btn-primary" [disabled]="!form.password || !form.email">Submit</button>

Try to -

<button type="submit" class="btn btn-primary [disabled]="loginForm.invalid">Submit</button>

or

<button type="submit" class="btn btn-primary" [disabled]="!loginForm?.valid">Submit</button>
Related