Establish predefined values for Angular Reactive Form using NgRx selector

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!

Answer №1

Based on the code provided, it seems that you are updating the control's value with the state from the store, which results in selecting everything again.

There are a few options to consider in this scenario. Essentially, you should only assign the entire array to the control's value if there is no existing value (meaning nothing is selected). If something is already selected, then it should be reused when there is an update from the Store.

// modify network array declaration
networks: Network[] = [];

this.store.select(selectNetworks).subscribe(networks => {
  this.networks = networks;
  const selected = this.form.get('selectedNetworks').getValue();

  const controlValue = selected.length > 0 ? selected : networks;  
  // or !!selected, as getValue() return may vary
  this.form.get('selectedNetworks').setValue(controlValue);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Master Checkbox in HTML Table Not Functioning for Selecting/Deselecting All Items

https://i.sstatic.net/RKWaC.png I'm facing an issue with my code that allows me to select and deselect multiple rows in a table. Specifically, I'm struggling with implementing a SELECTALL/DESELECTALL feature using a master checkbox. You can vie ...

Tips for accessing an AWS EC2 instance endpoint using HTTPS rather than HTTP

I am facing an issue with my Angular client (v14) trying to communicate with a Spring Boot application running on an AWS EC2 instance. The Angular app is hosted on Firebase and deployed under HTTPS. When attempting http calls in Angular using something lik ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

The issue arises as ContentChildren becomes undefined while trying to retrieve the data from the server

While I am loading data from the server and displaying it in ng-content, I am encountering an issue with making the first tab active by default. When using static content like the example below, the first tab is set as active without any problems: <app ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

Displaying a Jquery/bootstrap modal over a targeted Angular 5 component

In my Angular 5 project, I am utilizing a Bootstrap modal to display pop-up windows. However, the current implementation causes the modal to cover the entire screen which is not the desired behavior. Below is the layout code of my Angular application: &l ...

Is it possible to eradicate arrow functions in Angular CLI?

I am facing a challenge in running my code on IE11 due to issues with arrow functions. I need to find a way to eliminate them from the build and replace them with function() {}. Even though I have removed them from main.js, they are still present in the v ...

Yarn workspaces encounter an unexpected token error when exporting enums

I am currently working on a typescript project with the following structure: root/ packges/ client/ <-- Built with CRA server/ domain/ src/models package.json tsconfig.json webpack.config.js When trying to import a ...

Preventing unnecessary 'unused parameter' alerts in TypeScript

I've come across this scenario multiple times and have finally decided to explore the correct approach for handling it. When dealing with an abstract parent class that declares a method, and some concrete sub-classes implementing actual logic in their ...

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

What causes TypeScript to fail in inferring the types of function parameters?

class Base<T> { public state = {} as T; public getState(): T { return this.state } public setState(v: T) { this.state = v } } interface DogProps { name: 'hello'; age: 123; } class Dog extends Ba ...

How can I use Angular to download the HTML content of a component when a button is clicked?

Is there a way to generate and download an HTML report directly from a dialog box in Angular 13.2.5 without redirecting the user to a separate page? The dialog box collects user input, and I want a button labeled "Generate" at the bottom of the dialog box ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

Error: Unable to retrieve the value of 'secret' as it is undefined when attempting to assign a response cookie in Express framework

Today's operation that I've carried out countless times seems to be going awry. For some reason, I am unable to set a refresh token cookie using Express. Here is the error message in full /home/me/Code/apGymBE/node_modules/express/lib/response.j ...

Integrating SignalR into Angular 10 and ASP.NET: Enhancing Real

I've been trying to integrate SignalR into my ASP.NET (non-Core) and Angular (currently version 10) application. My Startup.cs file is utilizing Owin. Unfortunately, all the documentation and examples I've come across are either for ASP.NET Core ...

Using an existing function with no arguments as a handler in Typescript and React: A Step-by-Step Guide

NOTE: I'm still learning Typescript, so I may be missing something obvious here. Let's consider a basic scenario in React Javascript, using a Material-UI Button: // Closing dialog event handler without needing an 'event' argument const ...

Utilizing a TypeScript Variable as a Tagname in an HTML File within Angular

This specific problem is originally documented in this post. Despite being flagged as a duplicate, my scenario differs because the HTML content at hand is too extensive for utilizing innerHTML. The structure of my component's HTML file is as follows: ...

Using React with Typescript: How to pass a function as a prop to a child component and call it from within

I am trying to pass a function as a prop to a child component so that the child can call it. Here is my parent component: interface DateValue { dateValue: string; } const Page: React.FC = () => { const dateChanged = (value: DateValue) => { ...