Link a list separated by commas to checkboxes in Angular 9

Within my reactive form, I am binding a checkbox list to an array using the following structure: {id:number, name:string}.

TS

ngOnInit(): void {
 this.initFCForm();
 this.addCheckboxes();
}

initFCForm(): void {
this.fcForm = this.formBuilder.group({
  frequency : new FormControl('', [Validators.required]),
  rules: new FormArray([])
});
}

get rulesFormArray() {
  return this.fcForm.controls.rules as FormArray;
}
private addCheckboxes() {
  this.businessrules.forEach(() => this.rulesFormArray.push(new FormControl(false)));
}

HTML

 <label class="col-md-7" formArrayName="rules" 
         *ngFor="let rule of rulesFormArray.controls; let i = index">
               <input type="checkbox" [formControlName]="i">
                                    {{businessrules[i].name}}
  </label>

I now want to preselect the first and the third options when the page loads. However, using the code below only selects the first two options.

TS

this.fc.rules.patchValue([1,3])

Answer №1

When you use this.fc.rules.patchValue([1,3]), it assigns the value 1 to the first control of the rules FormArray and 3 to the second control of the rules FormArray, leaving the third control empty.

The Checkbox formcontrol requires a boolean value (true or false). When setting 1 and 3 using patch, the values are automatically interpreted as 'true' because they are truthy values.

If you want the first and third controls to be populated, you can try this:

this.fc.rules.patchValue([true, null, true])

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

I found that the Angular checkbox was only allowing me to select one value at a time instead of

Hey there, I am currently working on an angular tickbox where I want to be able to tick multiple values. However, I am facing an issue where only the latest checkbox value is displayed instead of both English and German together. How can I populate data fr ...

Error when running end-to-end tests in Angular CLI using the ng e2e

Recently, I created a new Angular 4 project using the Angular CLI. Upon running ng e2e, the sample end-to-end test worked flawlessly. However, when I later added a subfolder named services in the app folder and generated a service within it, the ng e2e com ...

Having trouble with errors when trying to implement react-router-v6 with typescript

Having trouble with my code and receiving the following error: "Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | ...

Removing curly braces and double quotes from an array object can be achieved by iterating through each element

Within this particular project, I have utilized Angular 8 and TypeScript. In the implementation, there exists an array that showcases emails either through user input or via CSV upload. Once the user inputs several emails, a button is available to send in ...

The Jasmine Angular PrimeNG test for WindowMaximizeIcon is encountering 16 failures

Currently in the process of upgrading my Angular application from version 15 to 16. Encountered an issue with my Jasmine test that involves PrimeNG's dialog. The error message is shown below: Chrome 114.0.0.0 (Windows 10) IncidentGridComponent should ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

Eliminating redundant values from a JSON object that is nested within another

Currently, I am working on rendering a list of Labels from a local JSON file. However, I am facing the issue of duplicates and I want each label to appear only once. I attempted to use Array.filter() and other methods to achieve this line: "Categories": ob ...

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

Encountering issues with Angular 4 dynamic routerlinks on server/localhost, while they work perfectly when the routerlink is

My goal is to create a dynamic navigation menu using a navigation menu service and component. To start, I built a prototype of the navigation menu with hardcoded HTML code like this: <nav> <md-list> <md-list-item rout ...

Is this a new issue in older R packages where class(x) returns both a matrix and array?

Working with an older package named PIMixture (link) has led me to encounter numerous errors within the code. The errors are similar to the example below: > library(PIMixture) > data(PIdata) > model<-"C_CIN3PLUS+L_CIN3PLUS+R_CIN3PLUS~RES_H ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...

Mastering the integration of NestJS with Redis for microservices

Currently, I am diving into the world of nestjs microservices. I am curious, what commands are available for me to use? const pattern = { cmd: 'get' }; this.client.send<any>(pattern, data) Additionally, how do I go about retrieving data ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

What is the reason for using a string as the index of an array in the following code?

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 78]; for(var index in arrayOfNumbers){ console.log(index+1); } The result produced by the given code snippet is as follows: 01 11 21 31 41 51 61 What is the reason behind JavaScript treating these ...

Passing data through Angular2 router: a comprehensive guide

I am currently developing a web application with the latest version of Angular (Angular v2.0.0). In my app, I have a sub-navigation and I want to pass data to a sub-page that loads its own component through the router-outlet. According to Angular 2 docume ...

Using NPM in combination with React and TypeScript to incorporate AMD modules

I am currently in the process of setting up a development environment for an application that is written in TypeScript using React. I already have existing TypeScript code that compiles to ES5 and AMD modules. My goal is to avoid any JavaScript transpilat ...

Managing the subscription function within the change event of a select tag in Angular 5 to prevent it from triggering repeatedly

Here is my DataService.ts: export class DataService { dataObs$: any; constructor(private http: HttpClient) { } getUsers() { return this.http.get('https://jsonplaceholder.typicode.com/users'); } getPostsById(id: number, refresh: boolean = ...