Disable Input fields in reactive form

后端 未结 16 893
暖寄归人
暖寄归人 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 20:51

    If to use disabled form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!

    (And if you are using on submit button like [disabled]="!form.valid"it will exclude your field from validation)

    0 讨论(0)
  • 2020-12-22 20:53

    To make a field disable and enable of reactive form angular 2+

    1.To disable

    • Add [attr.disabled]="true" to input.

    <input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">

    To enable

    export class InformationSectionComponent {
    formname = this.formbuilder.group({
    firstname: ['']
    });
    }
    

    Enable whole form

    this.formname.enable();

    Enable particular field alone

    this.formname.controls.firstname.enable();

    same for disable, replace enable() with disable().

    This Works fine. Comment for queries.

    0 讨论(0)
  • 2020-12-22 20:57

    A more general approach would be.

    // Variable/Flag declare
    public formDisabled = false;
    
    // Form init
    this.form = new FormGroup({
      name: new FormControl({value: '', disabled: this.formDisabled}, 
        Validators.required),
     });
    
    // Enable/disable form control
    public toggleFormState() {
        this.formDisabled = !this.formDisabled;
        const state = this.formDisabled ? 'disable' : 'enable';
    
        Object.keys(this.form.controls).forEach((controlName) => {
            this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'
        });
    }
    
    0 讨论(0)
  • 2020-12-22 20:57
    this.form.enable()
    this.form.disable()
    

    Or formcontrol 'first'

    this.form.get('first').enable()
    this.form.get('first').disable()
    

    You can set disable or enable on initial set.

     first: new FormControl({disabled: true}, Validators.required)
    
    0 讨论(0)
  • 2020-12-22 20:59

    I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean

     <fieldset [disabled]="isAnonymous">
        <label class="control-label" for="firstName">FirstName</label>
        <input class="form-control" id="firstName" type="text" formControlName="firstName" />
     </fieldset>
    
    0 讨论(0)
  • 2020-12-22 20:59

    I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).

    In my case I had to reset my form before reloading:

    this.form = undefined; this.router.navigate([path]);

    0 讨论(0)
提交回复
热议问题