首页 > 解决方案 > 如何简化禁用/启用控制角度

问题描述

我有很多功能,例如:

changeScondPlace(event) {
    if(event.checked == false) {
      this.GeofencingSection.controls['location2longer'].disable();
      this.GeofencingSection.controls['location2'].disable();
      this.GeofencingSection.controls['location2days'].disable();
      this.GeofencingSection.controls['picker2locationstart'].disable();
      this.GeofencingSection.controls['picker2locationend'].disable();
      this.GeofencingSection.controls['location2placement'].disable();
    } else {
      this.GeofencingSection.controls['location2longer'].enable();
      this.GeofencingSection.controls['location2'].enable();
      this.GeofencingSection.controls['location2days'].enable();
      this.GeofencingSection.controls['picker2locationstart'].enable();
      this.GeofencingSection.controls['picker2locationend'].enable();
      this.GeofencingSection.controls['location2placement'].enable();
    }
  }

此功能将通过单击复选框将输入状态从禁用更改为启用或从启用更改为禁用。

我试过了

 this.GeofencingSection.controls['location2longer'].enable = event.checked;
      this.GeofencingSection.controls['location2'].enable = event.checked;
      this.GeofencingSection.controls['location2days'].enable = event.checked;
      this.GeofencingSection.controls['picker2locationstart'].enable = event.checked;
      this.GeofencingSection.controls['picker2locationend'].enable = event.checked;
      this.GeofencingSection.controls['location2placement'].enable = event.checked;

伙计们有没有办法简化该代码?

标签: angulartypescript

解决方案


changeScondPlace(event) {
if(event.checked == false) {
  this.GeofencingSection.controls['location2longer'].disable();
  this.GeofencingSection.controls['location2'].disable();
  this.GeofencingSection.controls['location2days'].disable();
  this.GeofencingSection.controls['picker2locationstart'].disable();
  this.GeofencingSection.controls['picker2locationend'].disable();
  this.GeofencingSection.controls['location2placement'].disable();
} else {
  this.GeofencingSection.controls['location2longer'].enable();
  this.GeofencingSection.controls['location2'].enable();
  this.GeofencingSection.controls['location2days'].enable();
  this.GeofencingSection.controls['picker2locationstart'].enable();
  this.GeofencingSection.controls['picker2locationend'].enable();
  this.GeofencingSection.controls['location2placement'].enable();
}

}

如果这些是您表单中的所有字段,您可以简单地尝试:

this.GeofencingSection.disable();

和 this.GeofencingSection.enable();

如果这些元素不是表单中的唯一元素,并且还有其他元素,那么也许您可以将这些控件放入this.GeofencingSection对象中的一个组中。在这种情况下,如果您的组名是“someGroup”,您需要执行以下操作:

this.GeofencingSection.controls['someGroup'].disable();

和 this.GeofencingSection.controls['someGroup'].enable(); 该组下的所有表单控件将被禁用或启用。


推荐阅读