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!
The disabled attribute is a boolean attribute. When present, it specifies that the button should be disabled. A disabled button is unusable and un-clickable. The disabled attribute can be set to keep a user from clicking on the button until some other condition has been met (like selecting a checkbox, etc.).
You can enable or disable the ButtonGroup for Angular. By default, the component is enabled. To disable the whole group of buttons, set the disabled attribute of the ButtonGroup to true . To disable a specific button, set its own disabled attribute to true and leave the disabled attribute of the ButtonGroup undefined.
You can just add "disabled" to your button, and then when the user locks in their answer, enable it again. Additionally, it's not best practice to split your JavaScript into a bunch of different script tags. Put them all in one place.
Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With