how avoid to fire a valueChange after execute a form.reset?

Viewed 1767

I need to avoid firing a valueChange after executing a form.reset

userForm: FormGroup;

this.userForm.reset({ emitEvent: false });

private roleValueChanges() {
    this.userForm.controls.role.valueChanges.subscribe(roleId => {
       this.rolesService.get(roleId);
   }
}

Despite of emitEvent: false, when .reset the form, the valueChange is being fired. Any idea to avoid it?

I found this solution that works for me:

Object.keys(this.userForm.controls).forEach( fc => {
  this.userForm.get(fc).reset(null, {onlySelf: true, emitEvent: false});
  });
2 Answers

The reset per documentation:

reset(value: any = {}, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

As you can see, the first option in reset is the value, so currently you are telling the form that it should reset the formcontrol emitEvent to false. Instead in this case when you are using emitEvent you also need to tell the value to the form, in this case most likely an empty object will suffice.

So change the function to:

this.userForm.reset({}, { emitEvent: false });

DEMO for your reference, watch the console on submit, where the form is reset and valueChanges is not fired.

Related