Angular2 Reactive Forms - 根据条件动态禁用表单控制

Angular2 Reactive Forms - Disable form control dynamically from condition

我有一个 select 控件,我想根据条件动态禁用它:

this.activityForm = this.formBuilder.group({
  docType: [{ value: '2', disabled: this.activeCategory != 'document' }, Validators.required]
});

但是,即使在某些时候 this.activeCategory 变为 'document',docType 也不会启用。

我该如何解决这个问题?

您必须以不同于处理其他 HTML 元素的方式处理 select 元素。当 this.activeCategory 更改时,您将必须执行重置。

像这样:

this.activityForm.controls['docType'].reset({ value: '2', disabled: false });

当然,您可能希望使用当前值,而不是硬编码 '2'

如果需要(可能会),也可以禁用它。

this.activityForm.controls['docType'].reset({ value: '2', disabled: true });

有关 ng 表单控件的更多信息 reset

因为我不知道你是如何操纵activeCategory(也许它也是一个FormControl?),我会建议以下方法:

您可以使用(change)检测this.activeCategory何时发生变化,如下:

1 - 如果您使用 ngModel:

<input type="text" [(ngModel)]="activeCategory" (change)="checkValue($event)">

2 - 如果是 FormControl:

<input type="text" formControlName="activeCategory" (change)="checkValue($event)">

因此,在组件中,您可以使用 disable/enable 方法操作 docType control

checkValue(event: Event) {
  const ctrl = this.activityForm.get('docType');

  if (event.value === 'document') {
    ctrl.enable();
  } else {
    ctrl.disable();
  }
}

this.activityForm.controls['docType'].disable();

从 .ts 文件中,您可以从控件向您的文件添加键, 并在那里添加项目 disabled:true (停用表单项目) 或 false(激活表单项)

.ts

public form_name=new FormGroup({

              series: new FormControl({value: '', disabled: true}),
              inten: new FormControl({value: '', disabled: true}),
              rep: new FormControl({value: '', disabled: true}),
              rest: new FormControl({value: '', disabled: false}),
              observation: new FormControl({value: '', disabled: false}),



  });

.html

<form  [formGroup]="form_name" >

                                          <label for="series"  >Series</label>
                                           <input type="text" formControlName="series" >

                                          <label for="inten"  >Inten</label>
                                           <input type="text" formControlName="inten" >

                                          <label for="rep"  >Rep</label>
                                           <input type="text" formControlName="rep" >

                                           <label for="rest"  >rest</label>
                                            <textarea formControlName="rest" rows="3" cols="30" ></textarea>


                    </form>

您可以在此处使用三元运算符来有条件地禁用表单控件。

this.activityForm = this.formBuilder.group({
docType: [{ value: '2', disabled: this.activeCategory != 'document' ? true : false }, Validators.required]
});