Angular Reactive Form - Control disable()

240 views Asked by At

I can't find a solution to my specific Problem i have my Reactive Form where i want to disable select field based on radio element change and disable() function is not working.

Here is my form:

  ngOnInit() {
    this.createForm();
  } 

  createForm(): void {
    this.bsiNotesForm = this.formBuilder.group({
      searchType: new FormControl(this.searchCriteriaEnum.AllNotes),
      newNotes: new FormControl(false),
      bsiNumberToSearch: new FormControl(''),
      modelsToSearch: new FormControl({ value: '', disabled: true }),
    });
  }

Here is the toggle Function where im trying to disable the Select Field when the searchType is equals to searchCriteriaEnum.AllNotes

  toggleSearchType() {
    const searchType = this.bsiNotesForm.get('searchType')?.value;
    if (searchType === this.searchCriteriaEnum.ByModel) {
      console.log(searchType)
      this.bsiNotesForm.get('modelsToSearch')?.enable();
    } else {
      this.bsiNotesForm.get('modelsToSearch')?.disable();
      console.log(searchType)
      this.bsiNotesForm.get('modelsToSearch')?.reset();
    }
  }

here is the select and radio template


 <custom-select
  [name]="'modelsToSearch'"
  formControlName="modelsToSearch"
  [options]="modelsData"
 >
 </custom-select>

 <custom-radio
  [options]="[
  { value: searchCriteriaEnum.AllNotes, label: 'All Notes' },
  { value: searchCriteriaEnum.ByModel, label: 'By Model' }]"
  formControlName="searchType"
  (change)="toggleSearchType()"
  >
 </custom-radio>

if i need to provide more code and explanation feel free to ask !

2

There are 2 answers

0
Bartheus On BEST ANSWER

Sorry for not answering the comments i was working on other parts of my application. I found solution to my Problem with help of this topic Angular 2 - Custom Form Control - Disable

The problem was that i didnt used the setDisbledState() function in my custom select component. It is important when we are working with Control Value Accessor.

TS file:

    disabled = false;

    setDisabledState(isDisabled: boolean) {
        this.disabled = isDisabled;
    }

HTML file:

     <select [disabled]="disabled" >
        <option> ... </option>
     </select>
     
3
Erfan Farhadi On

What I understood is that you need to disable and enable the modelsToSearch field of your form depending on the change in the custom-radio selection. This seems okay, but since you have both custom-radio and custom-select fields, I am worried about a potential issue in their implementation. Another thing to consider is subscribing to the searchType valueChanges.