Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular form.statusChanges not working with dynamic form + asyncValidation

Tags:

angular

When dynamically adding a new FormControl with asyncValidation to a reactive form the form goes from PENDING to VALID/INVALID but statusChanges is not trigger.

I have a form that is dynamically modified and, after that happen, I subscribe to statusChanges. I'm printing the form's status and I can check that the status changes but stausChanges is not trigger.

Here is an example https://stackblitz.com/edit/angular-pvebmb?file=src%2Fapp%2Fapp.component.ts .

In this example you can check that there is a subscription to console.log for statusChanges. There is a button that, when clicked, adds a new FormControl with a async validation that takes 1 second to complete. You can check that, when you click in the button the form's status (that is printed in the html) goes from PENDING to INVALID but no console.log related to the statusChanges is printed.

I expected to get statusChanges triggered every time the form's status value changes.

like image 742
tiagowanke Avatar asked Jun 20 '26 21:06

tiagowanke


1 Answers

It looks like it is done by design. It is not firing the status change because it is invalid on initialization (or on the first run of updateValueAndValidity), and if you check the code of FormControl, that event is going to be prevented to be emitted. You can check it here: https://github.com/angular/angular/blob/8.2.13/packages/forms/src/model.ts#L1275

As you can see, emitEvent is false.

This doesn't really solve your problem, but at least explains why is it happening. In your example, if you set the value to an empty value right after pushing the control, you will get that statusChange, because that time updateValueAndValidity will have emitEvent set to true. So a workAround would be setValue of the formControl to empty if you really want that statusChanges to fire on initialization.

like image 146
David G. Avatar answered Jun 23 '26 10:06

David G.