Angular2 Reactive Forms - 从条件动态禁用表单控件

fra*_*nco 14 angular2-forms angular

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

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

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

我该如何解决?

dev*_*033 33

既然我不知道你是怎么操纵的activeCategory(也许它也是一个FormControl?),我会建议采用以下方法:

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

1 - 如果您正在使用ngModel:

<input type="text" [(ngModel)]="activeCategory" (change)="checkValue($event)">
Run Code Online (Sandbox Code Playgroud)

2 - 如果是FormControl:

<input type="text" formControlName="activeCategory" (change)="checkValue($event)">
Run Code Online (Sandbox Code Playgroud)

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

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

  if (event.value === 'document') {
    ctrl.enable();
  } else {
    ctrl.disable();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 关于选项 2:如果它是 FormControl,我建议订阅 ``` this.form.get('activeCategory').valueChanges ``` 而不是将逻辑放在 DOM 上。 (2认同)

R. *_*rds 7

您必须以不同于其他HTML元素的方式处理选择元素.您必须在this.activeCategory更改时执行重置.

像这样的东西:

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

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

如果出现这种需要(也可能会),同样禁用它.

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

有关ng表单控件重置的更多信息.