切换反应式表单控件基于下拉所选值启用或禁用

问题描述:

我有一些输入和select元素的反应形式,作用是禁用或启用,因此输入要基于select的值.

I have a reactive form of some inputs and select element , the role is to disable or enable so input base on the value of select.

this.form.get('option').valueChanges.subscribe((value: string) => {

    if (value === 'value1') {
        this.form.get('input01').disable();
        this.form.get('input02').disable();
        this.form.get('input03').disable();
    } else {
        this.form.get('input01').enable();
        this.form.get('input02').enable();
        this.form.get('input03').enable();
    }
});

我的表单有10个类似的输入.所以我有10行代码来启用和10行代码来禁用.我一直在寻找一种将代码重构为setValue方法的方法,例如根据if条件中给出的值将表单的所有元素设置为禁用或启用,或者建议我是否还有其他更好的方法.

My form have 10 inputs like that. so I have 10 lines of code for enable and 10 lines of code for disable. I was looking for a way to refactor this code to something like setValue method like set all the elements of the form to disable or enable, based on the value given in if condition, or suggest me if there is any other better way.

谢谢;

您可以将所有关联的控件添加到FormGroup下,然后可以禁用和启用它们.

假设我们有以下HTML:

You can add all the associated controls under a FormGroup, and then you can just disable and enable them.

Let say we have this HTML:

<form [formGroup]="cForm" (submit)="submitForm(cForm.value)" novalidate>
    <button (click)="toggle()">Toggle</button>
    <br>
    <input formControlName="mainControl" type="text" name="mainControl" required />
    <div formGroupName="g1">
        <input formControlName="test" type="text" required />
    </div>
    <div formGroupName="g1">
        <input formControlName="test2" type="text" required />
    </div>
    <input type="submit" value="submit" [disabled]="!cForm.valid">
</form>

因此,我们有一个包含输入的表格,另一组包含两个输入,因此您只想禁用这两个输入.

代码:

So we have one form which contains input and another group of two inputs, so you want to disable only the two inputs.

Code:

this.cForm = this._fb.group({
  mainControl: [
    null,
    [Validators.required])
  ],
  g1: this._fb.group({
    test: [null, [Validators.required]],
    test2: [null, [Validators.required]]
  })
});
toggle = () => {
   const control = this.cForm.get("g1");
   if (control.disabled) {
     control.enable();
   } else {
     control.disable();
   }
}

因此,当我们按下顶部按钮时,将调用切换功能,并检查该组是否已禁用,然后启用该功能,反方向也相同.

我假设您不想禁用所有表单控件,而只是部分输入. 但是,如果您想禁用并启用整个表单,则可以摆脱另一个嵌套组,并对该组执行相同的操作.
对于您的情况,您需要执行相同的操作,而不是按钮切换,而必须在订阅中进行.
祝你好运!

So when we press on the top button, it is call the toggle function and its check if the group already disabled, then it enable it, and the same for the opposite direction.

I assumed that you dont want to disable all the form controls, just a portion of inputs. But if you do like to disable and enable the whole form, you can just get rid of the other nested group and do the same for the group.
In your case, you do the same, instead of the button toggle, your have to do it inside the subscription.
Good luck !