0

A login form is being created. The form is always invalid when I use reactive form validators. The code is as below

<form class="main__form" [formGroup]="registrationForm" (ngSubmit)="formSubmit()">
                   <div class="row">
                       <div class="col-md-6">
                           <div class="form-group">
                               <input type="text" class="form-control" id="firstName" aria-describedby="firstName" placeholder="John" required name="accountName" formControlName="accountName">
                               <label for="firstName">Account Name*</label>
                           </div>
                        </div>
                       <button type="submit"  [disabled]= "!registrationForm.valid" ><span> Submit Now!</span></button>
                   </div>
               </form>



The TS file is as below

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormControl,Validators } from '@angular/forms';


@Component({
  selector: 'app-loginform',
  templateUrl: './loginform.component.html',
  styleUrls: ['./loginform.component.css']
})
export class LoginformComponent implements OnInit {

  registrationForm = new FormGroup({
    accountName : new FormControl('', [Validators.required]),
})

formSubmit(){
    console.log(this.registrationForm.value)
  }


The submit button is always disabled. I am not able to submit.

9
  • after you write accountname submit button is enable or not Commented Feb 5, 2020 at 7:31
  • It is not getting enabled. The submit button is still disabled. Commented Feb 5, 2020 at 7:32
  • 1
    try with this [disabled]= "registrationForm.invalid" Commented Feb 5, 2020 at 7:33
  • Are you getting any error in console? Commented Feb 5, 2020 at 7:33
  • 1
    its working properly see here stackblitz.com/edit/… Commented Feb 5, 2020 at 7:43

1 Answer 1

2

You can enable/disable the button by checking the validity of your form:

<button type="submit" [disabled]="!disableBtn">Click</button>

Inside your component:

let disableBtn = false;

this. registrationForm.valueChanges 
            .subscribe((changedObj: any) => {
                 this.disableBtn = this. registrationForm.valid;
            });

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.