Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular (4): disable the whole form (group) instead of each input separately?

Tags:

angular

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..>?

like image 867
Deniss M. Avatar asked Sep 17 '17 11:09

Deniss M.


People also ask

How do I turn off form control and keep value?

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.

What is form group in angular?

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.


3 Answers

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()
  }
like image 71
alexKhymenko Avatar answered Oct 11 '22 08:10

alexKhymenko


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>
like image 39
Josh Avatar answered Oct 11 '22 08:10

Josh


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();
}
like image 2
Ben Avatar answered Oct 11 '22 10:10

Ben