nXn
nXn

Reputation: 954

Angular Reactive Form - Validation not Working

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.

Upvotes: 0

Views: 337

Answers (1)

Thivya Thogesan
Thivya Thogesan

Reputation: 216

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;
            });

Upvotes: 2

Related Questions