Angular2 Reactive Forms - 从条件动态禁用表单控制 [英] Angular2 Reactive Forms - Disable form control dynamically from condition

查看:28
本文介绍了Angular2 Reactive Forms - 从条件动态禁用表单控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a select control that I want to disable dynamically based on a condition:

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

然而,即使在某些时候 this.activeCategory 变成了文档",docType 也不会启用.

However, docType doesn't become enabled even though at some point this.activeCategory becomes 'document'.

我该如何解决这个问题?

How do I fix this?

推荐答案

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

Since I don't know how you're manipulating activeCategory (maybe it's also a FormControl?), I'll suggest the following approach:

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

You can use (change) to detect when this.activeCategory has changed, as below:

1 - 如果您使用 ngModel:

1 - If you're using ngModel:

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

2 - 如果是 FormControl:

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

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

So, in component, you can manipulate the docType control using disable/enable methods:

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

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

这篇关于Angular2 Reactive Forms - 从条件动态禁用表单控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆