How to disable button in angular 7

Kgn-web picture Kgn-web · Apr 23, 2019 · Viewed 36.7k times · Source

I have an Angular7 app & using Reactive Forms Module for validation & forms.

this is how my template looks like.

<div class="row" [formGroup]="jobForm">
<div class="form-group"
 [ngClass]="{'has-error': jobForm.get('jobTitle').errors && 
  (jobForm.get('jobTitle').touched || jobForm.get('jobTitle').dirty)  }">
  <input type="text" class="form-control" formControlName="jobTitle" />
  <span class="help-block" *ngIf="formError">
  {{ formError.jobTitle }}
</span>
</div>
 <br />
 <button type="button" class="btn btn-primary" disabled="jobTitle.errors.required"
(click)="submit(jobTitle,jobDesc)">Create</button>

component.ts

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

@Component({
selector: 'app-create-job',
templateUrl: './create-job.component.html',
styleUrls: ['./create-job.component.css']
})
export class CreateJobComponent implements OnInit {
 constructor(private fb: FormBuilder) {}
 jobForm: FormGroup;
 formError: any;
 validationMessages = {
  jobTitle: { required: 'Job Title required'},
  jobCode: { required: 'Job Coderequired'},
  };

 ngOnInit() {
  this.jobForm = this.fb.group({
  jobTitle: ['', Validators.required]
});
this.formError = {
  jobTitle: '', jobCode : ''
};
this.jobForm.valueChanges.subscribe(data => {
  this.logValidationError(this.jobForm);
});

}

There are such 2-3 input elements which has validation.

How can I disable the submit if any of the validation has error. I don't want to go one by one property as I did for one property.

I mean if formError has any error, keep the button disable & initially disable.

Thanks!

Answer

monstertjie_za picture monstertjie_za · Apr 23, 2019

You need to check whether the form is valid.

<button type="submit" [disabled]="!jobForm.valid">Submit</button>

Angular Reactive Forms