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

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

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

其他回答

禁用FormControl可以防止它在保存时出现在表单中。你可以把它设置为readonly属性。

你可以这样做:

HTML:

<select formArrayName="value" [readonly] = "disableSelect">

打字稿:

this.disableSelect = true;

细节

一个更普遍的方法是。

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

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

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

使响应式形式angular 2+的字段禁用和启用

1.禁用

添加[attr。Disabled]="true"输入。

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

要启用

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

启用整个表单

this.formname.enable ();

单独启用特定字段

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

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

这很好。查询的注释。

当使ReactiveForm:[定义属性disbaled在FormControl]

 'fieldName'= new FormControl({value:null,disabled:true})

html:

 <input type="text" aria-label="billNo" class="form-control" formControlName='fieldName'>