Is it possible to disable the whole form (group) in angular instead of doing it for every input separately?
Something like <input [disabled]="formNotValid"/>
but for a <form>
or a <div ngModelGroup..>
?
If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.
FormGroup is one of the four fundamental building blocks used to define forms in Angular, along with FormControl , FormArray , and FormRecord . When instantiating a FormGroup , pass in a collection of child controls as the first argument. The key for each child registers the name for the control.
If You use ReactiveForms just write
form: formGroup;
this.form.disable();
In case of ngForm you can write like this' created plunker
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<input name="first" ngModel required #first="ngModel">
<input name="last" ngModel>
<button>Submit</button>
</form>
<button (click)="disable(f)">Disable form</button>
disable(f) {
f.form.disable()
}
It could be considered hack-y, but you could use ngClass and css to apply a class that turns off pointer events for all inputs inside a container when conditions are met.
.disable-inputs {
pointer-events: none;
}
<form [ngClass]="{'disable-inputs':[true/false condition]}">
// input elements
</form>
Here is a solution that automatically disables all form-elements when the submit-button is clicked.
This solution applies to template-driven forms.
HTML:
<form #myForm="ngForm" (ngSubmit)="onFormSubmit( myForm )">
<input type="text" name="title" [(ngModel)]="model.title" #title="ngModel">
<button type="submit">
<span *ngIf="!imyForm.disabled">
Submit Form
<span>
<span *ngIf="myForm.disabled">
Submitted
<span>
</button>
</form>
TS:
public onFormSubmit( form: any): void {
form.form.disable();
}
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