angularangular-reactive-formsdisabled-control

Angular Reactive Form - Control disable()


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 !


Solution

  • 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>