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

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

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),
});

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


当前回答

在响应式表单的DOM中使用disable是不好的做法。 当初始化from时,你可以在FormControl中设置这个选项

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

不需要属性值

或者你可以使用get('control_name')来获取表单控件并设置为禁用

this.userForm.get('username').disable();

其他回答

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

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

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

我通过在字段集中包装我的输入对象的标签来解决它: 字段集应该将disabled属性绑定到布尔值

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

一个更普遍的方法是。

// 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'
    });
}

lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),

注意

如果你正在创建一个使用变量为条件的表单,并试图改变它之后,它将不会工作,即表单将不会改变。

例如

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

如果你改变变量

this.isDisabled = false;

形式不会改变。你应该使用

this.cardForm.get(数量).disable ();

BTW.

你应该使用patchValue方法来改变值:

this.cardForm.patchValue({
    number: '1703'
});