jo1718
jo1718

Reputation: 69

How to disable an input FormControl in a Reactive Form with a condition in Angular 15?

I have a form where I can input a student Id. Below that are two input boxes, full name and email. When I load the page, only the student Id input box should be enabled and the two inputs below it are disabled. When I enter the student Id and if it has a record, that's the only time that the input boxes for the full name and email are enabled.

When I used Angular 13, it was able to work with this for each input

[attr.disable]="!isStudentIdReal"

However, I recently updated to Angular 15 and this stopped working. I was able to find a solution where:

studentName : [{value: '', disable: true}],
email : [{value: '', disable: true}]

This disabled the input boxes however, it won't enable them because I don't have a condition.

Upvotes: 2

Views: 6322

Answers (4)

Muhammad Athaullah
Muhammad Athaullah

Reputation: 17

In your input tag in html:

[disabled]="!isStudentIdReal"

In your ts file:

enableOrDisable(){
  if(this.formgroupname.controls['id'].value){
    this.isStudentIdReal=true
  }else{
    this.isStudentIdReal=false
  }
}

call the above method in change of id input tag as well as in constructor or ngOnInIt.

Upvotes: -1

JuanDeLasNieves
JuanDeLasNieves

Reputation: 361

Using the ReactiveForms approach in Angular, every FormControl has a set of properties and methods. The ones you are looking for would be disable() and enable().

You can call them directly in the component, not the template, through the FormGroup that contains your controls.

Let's say your FormGroup is called studentInfo. You could add to your component some getters to access directly those controls:

get studentName() {
  return this.studentInfo.get('studentName');
}

get studentEmail() {
  return this.studentInfo.get('email');
}

Then, inside the method that checks the student ID you could write something like this:

  // code that checks student id
  if (!isStudentIdReal) {
    this.studentName.disable();
    this.studentEmail.disable();
  } else {
    this.studentName.enable();
    this.studentEmail.enable();
  }
  // rest of the code

This code can be written more elegantly, but I hope it helps you get the gist.

Upvotes: -1

Yogita Katte
Yogita Katte

Reputation: 59

Try this:

use [disabled]="!isStudentIdReal"

Upvotes: -1

Matthieu Riegler
Matthieu Riegler

Reputation: 55926

There is a breaking change about that in angular 15.

You will need to import the ReactiveFormsModule with a config to restore the previous behavior:

ReactiveFormsModule.withConfig({callSetDisabledState: 'whenDisabledForLegacyCode'})

The other possibility being calling enable() on the FormControl when the value of isStudentIdReal changes.

Upvotes: 5

Related Questions