Currently, I am developing an application using Angular and NgRx.
Within this application, I have implemented a reactive form where I need to pre-set default values for one of the form controls by fetching data from the store.
export class FormComponent implements OnInit {
networks: Network[];
form: FormGroup;
ngOnInit(): void {
this.form = this.fb.group({
selectedNetworks: ['', [Validators.required]],
...
});
this.store.select(selectNetworks).subscribe(networks => {
this.networks = networks;
this.form.get('selectedNetworks').setValue(networks);
});
}
<mat-select
formControlName="selectedNetworks"
multiple>
<mat-option
*ngFor="let n of networks"
[value]="n">
{{n.name}}
</mat-option>
</mat-select>
The multiselect dropdown menu displays a list of networks, with all networks initially selected as per requirements.
To retrieve the necessary networks, multiple HTTP requests are made (as mandated by the requirements) which update the ngrx store. The selectNetworks selector emits new values after each successful request. If two requests are needed to get all networks, the full list is only available after the second emission.
Additionally, there is a WebSocket event that triggers network updates (e.g., status changes). This event updates the ngrx store, causing the selectNetworks selector to emit again.
However, a challenge arises when the form is initialized with all networks selected, and then the user manually deselects one network before a WebSocket event occurs. In this scenario, the selectNetworks subscription re-selects all networks, overwriting the user's previous selection.
I've explored potential solutions involving the use of take(1), but due to the possibility of the initial emission not containing the complete network list, this approach does not suffice. Are you aware of any alternative solutions that could address this issue?
Thank you in advance!