Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable all the fields in a template driven form in angular

I created a template driven form in angular 5

I want to disable the whole form at first, and also want the form to be enabled once some button is clicked, Hence I added a disabled property in the form tag and made its value as false as shown below , (this didn't work though):

<form #formName = "ngForm" [disabled]="true">
</form>

As the above disabled property didn't work, I changed the disabled property as

[attr.disabled] = true

This also didn't work

Now as I have the form element's reference which is #formName, I used it in the TS file and tried to change the disabled property value inside the reference object

Here's what I have done :

@ViewChild('formName') formName;


this.formName.disabled = true; 

which also didn't work and I got an error message saying disabled cannot be changed as it is only a getter

How should I disable the whole form by default in angular on template driven forms ?

Thanks in advance :)

like image 446
Harish Avatar asked Mar 28 '18 11:03

Harish


People also ask

How do I reset a template in form driven?

Resetting a form in template-driven approach: In template driven approach, we need to import NgForm from '@angular/forms' and we use [(ngModel)] directive for two way data-binding and we should also import FormsModule from '@angular/forms' in app.

How do I reset a template driven in angular 10?

To reset template-driven form, NgForm provides resetForm() method that is called as following. To call the above function, create a button in UI. If we want to reset form with some default values, then assign the default values with form control name of the form.

What is the difference between template driven and reactive forms?

Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.


Video Answer


1 Answers

As mentioned in the comment you can wrap the form inside a fieldset tag and achieve this as below:

<form>
    <fieldset [disabled]="fieldsetDisabled">
        <!-- YOUR FIELDS HERE -->
    </fieldset>
</form>

And you can change handle the state in your controller by toggling a local variable and between the disabled/enabled states as:

this.fieldsetDisabled = true;  // Disables the fieldset
this.fieldsetDisabled = false; // Enables the fieldset
like image 176
Aravind Avatar answered Oct 19 '22 01:10

Aravind