Ben
Ben

Reputation: 911

enable/disable form control fires valueChanges Angular 2 Forms

Any ideas why when running the following code I get the valueChanges event of 'firstName' control fired?

let form: FormGroup = this.createForm();
form.controls['firstName'].enable();

form.controls['firstName'].valueChanges(value=>{
      //some code
});

As no value has changed (just the status), I wouldn't expect valueChanges to be triggered here, only the statusChanged.

Am I missing something?

Upvotes: 41

Views: 36112

Answers (4)

aw04
aw04

Reputation: 11187

No idea why it behaves as it does, but you can send emitEvent: false to enable/disable without firing valueChanges.

form.controls['firstName'].enable({ emitEvent: false });

Upvotes: 46

Petru Bantis
Petru Bantis

Reputation: 151

I have angular version 6.0.3

this.form.get('inputName').setValue(newValue, {onlySelf: true, emitEvent: false});

This works for me.

Upvotes: 15

Ashish
Ashish

Reputation: 74

ValueChange getting triggered on enabling or disabling a form in angular is a bug in their code.

If you dont want the ValueChange to be triggered on enabling or disabling the form, I found a workaround which may help.

Object.keys(this.toolForm.controls).forEach(key => {
    this.form.controls[key].enable({onlySelf: true, emitEvent: false});
});

The above code fixes the issue for me.

Upvotes: 1

Ali Shahzad
Ali Shahzad

Reputation: 5332

Basically complete form is mapped on a model, so whenever you enable/disable any control, the form model's property changes. And because the model is changing so valueChanges event will be triggered. I think its normal.

Upvotes: 29

Related Questions