Home > OS >  How can I subscribe to two input fields and make them toggle each other in Angular 2?
How can I subscribe to two input fields and make them toggle each other in Angular 2?

Time:10-27

I have a checkbox and input field,

Case One:

  • If the input field isn't empty checkbox will be disabled.
  • If the input field is empty checkbox will be enabled.

Case Two:

  • If the checkbox checked, Input field will be disabled.
  • f the checkbox isn't checked, Input field will be enabled.

here is angular html part;

<form [formGroup]="testForm">
    <div>
      <label for="veggieMustard">show Text</label>
      <input
      formControlName="showTextInput"
      id="showText"
      type="text"
      />
   </div>
   <div>
    <input
    formControlName="showCheckbox"
    id="showCheckBox"
    type="checkbox"
    />
    <label for="showCheckBox">show</label>
   </div>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Angular Controller:

import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  FormControl,
} from '@angular/forms';

@Component({
  selector: 'order-sheet',
  templateUrl: './test-form.component.html',
  styleUrls: ['./test-form.component.css'],
})
export class TestController implements OnInit {
  testForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {
    this.buildForm();
  }

  ngOnInit() {
    this.subscribeToShowTextInput();
    this.subscribeToShowCheckBox();
  }

  buildForm(): void {
    this.testForm = this.formBuilder.group(
      {
        showTextInput: this.formBuilder.control(null),
        showCheckbox: this.formBuilder.control(null),
      }

// To Disable or Enable the Checkbox depeneds on the input field status
  private subscribeToShowTextInput(): void {
    const showCheckbox = this.orderSheetForm.controls['showCheckbox'];
    this.orderSheetForm.controls['showTextInput'].valueChanges.subscribe(
      (value) => {
        if (value) {
          showCheckbox.disable();
        } else {
          showCheckbox.enable();
        }
        console.log(value);
      }
    );
  }

// To Disable or Enable the Input field depeneds on the Checkbox status
  private subscribeToShowCheckBox(): void {
    const showTextInput = this.orderSheetForm.controls['showTextInput'];
    this.orderSheetForm.controls['showCheckbox'].valueChanges.subscribe(
      (value) => {
        if (value) {
          showTextInput.setValue('');
          showTextInput.disable();
        } else {
          showTextInput.enable();
        }
        console.log(value);
      }
    );
  }}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I am getting this Error ERROR RangeError: Maximum call stack size exceeded Which happened because the subscription is always updating each other which gets me into infinite loop, if i disable one of the subscription it works fine,

Do anyone have any good idea to deal with such situation ?

I'm appreciating any suggestions, directing to documentations or article, because i spend days searching, but i did not find something useful to my situation.

Thank you in advance.

CodePudding user response:

You should pass in the emitEvent: false option when disabling and enabling the controls.


import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';

@Component({
  selector: 'form',
  templateUrl: 'form.component.html',
  styles: [],
})
export class FormComponent {
  form = this.fb.group({
    showCheckbox: new FormControl(),
    showTextInput: new FormControl(),
  });

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.subscribeToShowTextInput();
    this.subscribeToShowCheckBox();
  }

  private subscribeToShowTextInput(): void {
    this.showTextInput.valueChanges.subscribe((value) => {
      if (value) {
        this.showCheckbox.disable({ emitEvent: false });
      } else {
        this.showCheckbox.enable({ emitEvent: false });
      }
    });
  }

  private subscribeToShowCheckBox(): void {
    this.showCheckbox.valueChanges.subscribe((value) => {
      if (value) {
        this.showTextInput.setValue('');
        this.showTextInput.disable({ emitEvent: false });
      } else {
        this.showTextInput.enable({ emitEvent: false });
      }
    });
  }

  get showCheckbox() {
    return this.form.get('showCheckbox');
  }

  get showTextInput() {
    return this.form.get('showTextInput');
  }
}

  • Related