1

Hello I want to disable a filed/drop-down based on conditions angular form builder:

I have 3 drop downs, first drop down will be loading while page loading.. when I select the option in first drop-down second should be enabled, when I select the option in second third should be enabled.

here is what I tried:

       ngOnInit(): void {

            this.someMethodToFetchDataForSelectbox();
            this.method1.subscribe(data => {
                this.data= data;
              }
            );
            this.constructForm();
          }

    constructForm() {
    this.form =  this.fb.group({
     listOfFruits: [''],
     listOfAnimals: [''],
listOfLetters: ['']
    });
this.form.get('listOfAnimals').disable();
    this.form.get('listOfLetters').disable();
    this.form.controls.listOfFruits.valueChanges.subscribe(value=>{
   his.forms.controls.listOfAnimals.enable();
      this.form.get('listOfLetters').disable(); 
//method to fetch list of animals from DB
fetchAnimals(value) ;

    });
    }
fetchAnimals(value) {
 this.form.controls.listOfAnimals.valueChanges.subscribe(value=>{
   this.forms.controls.listOfLetters.enable();
      //method to fetch list of letters from DB
fetchLetters(value) ;
  });
}

I tried the above but it is not working..

2 Answers 2

3

you need to use valueChange property not value

this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  //...
})

in case of disable the form control by default

constructForm() {
 this.form =  this.fb.group({
  listOfFruits: [''],
  listOfAnimals: ['']
 });

 this.form.get('listOfAnimals').disable(); // 👈
 ....
}
Sign up to request clarification or add additional context in comments.

4 Comments

worked thanks :), small question how to disable the filed by default here
happy to help , I have updated the answer for disable the form control @user2108383 👍
@user2108383 in case this answer solve your problem it's will be could you mark it as answered ,so the question doesn't appear in unanswered questions in the search result 👍
@malbaarmawi, I have a quick requirement I edited the question.. trying form last 5-6 hours couldn't find the solution :( can you please help me .. I edited the question..
0

in additions to @malbarmawi's answer make listOfAnimals disable initially

this.form =  this.fb.group({
 listOfFruits: [''],
 listOfAnimals: [{value: '', disabled:true}]
});

this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  (value) ? this.form.controls.listOfAnimals.enable() : this.form.controls.listOfAnimals.disable()
});

1 Comment

some how this is not working to disable by default . listOfAnimals: [{value: '', disabled:true}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.