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

Time:06-01

login.component.html

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

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

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

<button type="submit"  [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

CodePudding user response:

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

Template:

[disabled]="invalidForm()"

Ts:

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

CodePudding user response:

Try this if the other answers don't work.

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

CodePudding user response:

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"

  • Related