Reputation: 7555
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!
Upvotes: 18
Views: 106182
Reputation: 378
You must to check is the form is valid or not.
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<input required name="uri" [(ngModel)]="data">
<button [disabled]="!f.valid">Submut</button>
</form>
Upvotes: 2
Reputation: 91
Try this code:
<button type="button" class="btn btn-primary" [disabled]="jobForm.form.invalid"
(click)="submit(jobTitle,jobDesc)">Create</button>
Upvotes: 5
Reputation: 4841
You need to use ternary operator as disabled accepts true and null to work properly
<button
type="button"
class="btn btn-primary"
[disabled]="jobTitle.errors.required? true: null"
(click)="submit(jobTitle,jobDesc)">
Create
</button>
Upvotes: 9
Reputation: 1768
Just make the button rely on the validity of the form.
This will take care of errors as well as pristine (initial) condition.
Example:
<button type="button" class="btn btn-primary" [disabled]="!jobForm.valid"
(click)="submit(jobTitle,jobDesc)">Create</button>
Upvotes: 0
Reputation: 7803
You need to check whether the form is valid
.
<button type="submit" [disabled]="!jobForm.valid">Submit</button>
Upvotes: 23