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

查看:83
本文介绍了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]
});

但是,即使在某些时候docType也没有启用.activeCategory变成了文档".

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

我该如何解决?

推荐答案

由于我不知道您如何操作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 控件:

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天全站免登陆