Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Angular2 Reactive Form control enable state change

Tags:

I have a form with first_name and last_name fields.

When both of these fields have a value entered, I wish to enable another formControl in the same form.

I know I can subscribe to the changes like this:

  createForm() {
    this.myForm = new FormGroup({
      first_name: this.first_name,
      last_name: this.last_name,
      email: this.email,
      mobile: this.mobile,
      salutation: this.salutation
    });
    this.myForm.valueChanges.subscribe(data => console.log('form changes', (!data.first_name == !data.last_name)));
  }

which logs to the console and shows 'true' when both values are set.

You can see from this thread on angular github that we cannot/should not set that to a property and bind [disabled]=<booleanProperty> (and the core team seem to still be working on this issue).

So how do I use the result from my valueChanges stream above to actually set the other control to an enabled state?

In the OnInit it is disabled as per the guides:

this.salutation = new FormControl({value:'', disabled: true}, Validators.required); 

UPDATE

Sorry I forgot to mention that I already tried this, in the OnInit:

this.myForm.valueChanges.subscribe(data => {
  if (!data.first_name == !data.last_name) {
    this.salutation.enable();
  };
}) 

That does not work, it throws console error: Maximum call stack size exceeded

like image 949
rmcsharry Avatar asked Dec 19 '16 17:12

rmcsharry


People also ask

How do I disable FormControl in Angular 7 dynamically?

Using [disable] Binding We can disable a control using [disabled]="true" binding. We can also disable control using [attr. disabled]="true" . Angular does not suggest to use [disabled]="true" binding to disable a control.

How do I turn off form control and keep value?

If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.


1 Answers

The stack size exceeded was the clue to solving this. Since the stream is 'continuous' my code kept setting the control to enabled - but of course, it only needs to be enabled once.

So adding a check solved the problem, and now it works:

this.myForm.valueChanges.subscribe(data => {
  if (!data.first_name == !data.last_name && this.myForm.controls['salutation'].disabled) {
    this.myForm.controls['salutation'].enable();
  };
}) 

Further info here

like image 111
rmcsharry Avatar answered Sep 24 '22 17:09

rmcsharry