我已经试着从这里效仿其他答案,但我没有成功!

我创建了一个响应式表单(即,动态),我想在任何给定的时间禁用一些字段。我的表单代码:

this.form = this._fb.group({
  name: ['', Validators.required],
  options: this._fb.array([])
});

const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
  value: ['']
}));

我的html:

<div class='row' formArrayName="options">
  <div *ngFor="let opt of form.controls.options.controls; let i=index">
    <div [formGroupName]="i">
      <select formArrayName="value">
        <option></option>
        <option>{{ opt.controls.value }}</option>
      </select>
    </div>
  </div>
</div>

为了方便起见,我简化了代码。我想禁用类型选择字段。我试着这样做:

form = new FormGroup({
  first: new FormControl({value: '', disabled: true}, Validators.required),
});

不工作!有人有什么建议吗?


当前回答

我试图从localstorage获取值,我想要禁用电子邮件和密码字段。这招对我很管用:

email: new FormControl({value: localStorage.getItem("email"), disabled:true},[
      Validators.required,
      Validators.minLength(3),
    ]),
password: new FormControl({value: localStorage.getItem("password"), disabled:true},[
      Validators.required,
      Validators.minLength(3),
    ])

其他回答

我试图从localstorage获取值,我想要禁用电子邮件和密码字段。这招对我很管用:

email: new FormControl({value: localStorage.getItem("email"), disabled:true},[
      Validators.required,
      Validators.minLength(3),
    ]),
password: new FormControl({value: localStorage.getItem("password"), disabled:true},[
      Validators.required,
      Validators.minLength(3),
    ])

最好的解决方案是:

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

解决方案大纲(如果断开链接):

(1)创建指令

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 ) {}
}

像这样使用它

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

(3)由于禁用的输入不显示在表单中。值提交时,您可能需要使用以下代替(如果需要):

onSubmit(form) {
  const formValue = form.getRawValue() // gets form.value including disabled controls
  console.log(formValue)
}
name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],

or

this.form.controls['name'].disable();

我有同样的问题,但调用this.form.controls['name'].disable()没有修复它,因为我正在重新加载我的视图(使用router.navigate())。

在我的情况下,我必须重置我的表单之前重新加载:

这一点。Form = undefined; this.router.navigate((路径));

你可以声明一个函数来启用/禁用所有的表单控件:

  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]();
    });
  }

像这样使用它

// disbale all field but email
this.toggleDisableFormControl(true, ['email']);