Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
Ben Avatar asked Mar 15 '17 11:03

Ben


People also ask

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.


2 Answers

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 }); 
like image 86
aw04 Avatar answered Nov 01 '22 14:11

aw04


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.

like image 43
Ali Shahzad Avatar answered Nov 01 '22 15:11

Ali Shahzad