Disable Input fields in reactive form

后端 未结 16 894
暖寄归人
暖寄归人 2020-12-22 20:28

I already tried to follow the example of other answers from here and I did not succeed!

I created a reactive form (ie, dynamic) and I want to disable some fields at

相关标签:
16条回答
  • 2020-12-22 21:10
    setTimeout(() => { emailGroup.disable(); });
    
    0 讨论(0)
  • 2020-12-22 21:11

    The disabling FormControl prevents it to be present in a form while saving. You can just set it the readonly property.

    And you can achieve it this way :

    HTML :

    <select formArrayName="value" [readonly] = "disableSelect">
    

    TS :

    this.disbaleSelect = true;
    

    Found this here

    0 讨论(0)
  • 2020-12-22 21:11

    You can declare a function to enable/disable all of the form control:

      toggleDisableFormControl(value: Boolean, exclude = []) {
        const state = value ? 'disable' : 'enable';
        Object.keys(this.profileForm.controls).forEach((controlName) => {
          if (!exclude.includes(controlName))
            this.profileForm.controls[controlName][state]();
        });
      }
    

    and use it like this

    this.toggleDisableFormControl(true, ['email']);
    // disbale all field but email
    
    0 讨论(0)
  • 2020-12-22 21:13

    Pay attention

    If you are creating a form using a variable for condition and trying to change it later it will not work, i.e. the form will not change.

    For example

    this.isDisabled = true;
    
    this.cardForm = this.fb.group({
        'number': [{value: null, disabled: this.isDisabled},
    });
    

    and if you change the variable

    this.isDisabled = false;
    

    the form will not change. You should use

    this.cardForm.get('number').disable();

    BTW.

    You should use patchValue method for changing value:

    this.cardForm.patchValue({
        'number': '1703'
    });
    
    0 讨论(0)
提交回复
热议问题