I have a form with checkboxes that get created based on what comes back from an API call. When the API returns data, I need to make these checkboxes required fields. But if the API returns nothing, then the checkboxes should not be required.
The problem is my code keeps running before the API finishes. This means my checkboxes always end up as not required since the data hasn’t loaded yet.
Had this exact problem with Angular reactive forms last month. The issue is your validation runs synchronously right after creating the subscription, but the Observable is asynchronous. So this.UserGroups = response; only happens when the HTTP request finishes - could be milliseconds or seconds later depending on your network. Your validation runs immediately while UserGroups is still empty. Move the validation into the subscribe block like others said, but also consider using the finalize operator for loading states. Don’t forget to call updateValueAndValidity() after changing validators or the form control won’t reflect the new rules.
This happens because HTTP calls are async. Your validation runs right after you subscribe, but the API response hasn’t come back yet. I faced a similar issue while building a dynamic form system last year. You need to move your validation logic inside the subscribe callback. This ensures it only runs after the API response arrives and the UserGroups array actually has data. Furthermore, if your form structure depends on the API data, consider placing the buildForm call inside the subscription to avoid race conditions between the form setup and data loading.
move that validation logic inside the subscribe block! you’re checking UserGroups.length before the API responds. just put the if/else statement right after this.UserGroups = response; and you’re good to go.