Disable Input fields in reactive form

后端 未结 16 895
暖寄归人
暖寄归人 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:01
    name: [{value: '', disabled: true}, Validators.required],
    name: [{value: '', disabled: this.isDisabled}, Validators.required],
    

    or

    this.form.controls['name'].disable();
    
    0 讨论(0)
  • 2020-12-22 21:05

    The best solution is here:

    https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110

    Outline of solution (in case of broken link):

    (1) Create a directive

    import { NgControl } from '@angular/forms';
    
    @Directive({selector: '[disableControl]'})
    export class DisableControlDirective {
    
      @Input() set disableControl( condition : boolean ) {
        const action = condition ? 'disable' : 'enable';
        this.ngControl.control[action]();
      }
    
      constructor( private ngControl : NgControl ) {}
    }
    

    (2) Use it like so

    <input [formControl]="formControl" [disableControl]="condition">
    

    (3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):

    onSubmit(form) {
      const formValue = form.getRawValue() // gets form.value including disabled controls
      console.log(formValue)
    }
    
    0 讨论(0)
  • 2020-12-22 21:08

    It is bad practice to use disable in a DOM with reactive forms. You can set this option in your FormControl, when you init the from

    username: new FormControl(
      {
        value: this.modelUser.Email,
        disabled: true
      },
      [
        Validators.required,
        Validators.minLength(3),
        Validators.maxLength(99)
      ]
    );
    

    Property value is not necessary

    Or you can get your form control with get('control_name')and set disable

    this.userForm.get('username').disable();
    
    0 讨论(0)
  • 2020-12-22 21:08

    lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),
    
    0 讨论(0)
  • 2020-12-22 21:09

    If you want to disable first(formcontrol) then you can use below statement.

    this.form.first.disable();

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

    This worked for me: this.form.get('first').disable({onlySelf: true});

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