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

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

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

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


当前回答

我只是用

<input type="text" formControlName="firstName" [attr.disabled]="true || null" />

在此情况下,firstName在form.value中保持可访问

重要提示:你必须使用|| null作为默认值,这样angular才能一起删除该属性。

其他回答

注意

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

例如

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'
});
name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],

or

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

如果要使用禁用的表单输入元素(如正确答案中建议的那样) 如何禁用输入)验证他们也将被禁用,请注意!

(如果你使用的是提交按钮,如[disabled]="!Valid "它会将你的字段排除在验证之外)

我试图从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),
    ])

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

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