How to check all checkboxes in Angular using ngFor and ngIf?

Is there a way to select all checkboxes in an Angular form that uses ngFor and ngIf? I want to activate all checkboxes for the months when I click on "Select All". The list of months is stored in an array.

Click here to see the HTML representation of the code.

<div class="form-group row">
     <label class="col-2 col-form-label">Meses de siembra</label>
         <div class="col-8">
             <table>
                 <tr>
                     <label>
                         <input type="checkbox" ng-model name="seleccionarTodo"> Select All
                     </label>
                 </tr>
                 <tr>
                     <td>
                         <div *ngFor="let m of mesesSiembra; let i=index">
                             <label *ngIf="i<6">
                             <input type="checkbox" ng-model name="mes1a6"> {{m.nombre}}
                             </label>
                         </div>
                     </td>
                     <td>
                         <div *ngFor="let m of mesesSiembra; let i=index">
                             <label *ngIf="i>5">
                                 <input type="checkbox" ng-model name="mes7a12"> {{m.nombre}}
                             </label>
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
</div>

Answer №1

Every entry in the "mesesSiembra" array should have a boolean property that represents the checked state of the checkbox. To bind this property, use [checked]="m.checked" and (click)="m.checked = !m.checked". Additionally, ensure that each form element has a unique name by appending the index to the name attribute like so: [name]="'mes_' + i".

To check all the checkboxes at once, you can create a function that performs the following:

this.mesesSiembra = this.mesesSiembra.map(m => ({ ...m, checked: true }));

For a working example, refer to the following demo: https://stackblitz.com/edit/angular-ivy-ibqzjj?file=src%2Fapp%2Fapp.component.html

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

Angular: Granting an external module access to a provider

One of the modules I imported provides a service with an optional dependency. Although it being optional didn't affect my application, as it just prevented any errors from occurring when not present. Here's an example: import { FooModule } from ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

Customizing the background color of a Material-UI checkbox

I am currently working with Material UI checkboxes. I want to customize the background color of the checkbox, but setting the root background to white creates a rounded shape that doesn't match my intended design. Is there a way to change the shape of ...

Revealing a single element in an Angular 6 application that is utilized by several modules

As I am in the process of breaking down a large module into smaller ones, I have encountered an issue that needs to be addressed. Here are the specifics: The Search component is currently being used across multiple components. Initially, it was declared i ...

fakeAsync failing to synchronize with async task completion

Scenario In my testing process, I am evaluating a component that utilizes an observable-based service to retrieve and display data for internationalization purposes. The i18n service is custom-made to cater to specific requirements. While the component ...

Flex-Layout in Angular - The Ultimate Combination

Recently, I decided to delve into Angular and the Flex-Layout framework. After installing flex-layout through npm, I proceeded to import it in my app.module.ts file like so: import { FlexLayoutModule } from '@angular/flex-layout'; imports: [ Fl ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

Utilizing enum values in the HTML value attribute with Angular 2

I'm attempting to utilize an enum value in order to set the selected value of an HTML attribute: export enum MyEnum { FirstValue, SecondValue } export function MyEnumAware(constructor: Function) { constructor.prototype.MyEnum = MyEnum; } ...

I possess legacy Angular 1 code in which I implemented div styles. How can I replicate the same functionality in Angular 11?

Recently, I have been revamping an older project and encountered a challenge in setting the style of an array where each point needs to have a unique position. The Divs are all identified by id = obj.id, and I must assign specific left and top values to ea ...

Unable to access API hosted on localhost from Angular Client integrated with C# Backend running on a standalone server unit

I have an Angular Client (v14) and a .Net 6 WebAPI running on separate projects within a Raspberry Pi. The setup is for a standalone kiosk where both the front end and backend are hosted on the same device. My goal is to access the front end from a PC on ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

Using Angular and Okta together can bring a seamless experience for your users. Learn how to properly use the redirect

I have integrated Okta for user authentication in my Angular 13 application. I followed the guidelines provided by Okta to utilize their SDK, but I am facing issues defining the redirectionUrl with the HashLocationStrategy. Upon logging in, I encounter a ...

Is ngForIn a valid directive in Angular 4?

While attempting to loop over the properties of an object using *ngFor with in, I encountered a challenge. Here is a sample code snippet: @Controller({ selector: 'sample-controller', template: ` <ul> <li *ngFor="let i in o ...

Circular Dependency Detected in Angular 7 Library: A Tight Web of Directive, Service, and Module Interconnections

After setting up a new Angular 7 project with a library that includes a directive, a service, and a module (where the directive gets the service injected and the service has an injectionToken exported in the module), I encountered these warnings during com ...

Removing special characters when pasting into text box in Angular 2 or higher versions

To ensure that special characters are trimmed or removed when pasting into a textbox inside the TypeScript component file (with extension .ts), utilize a function within the TypeScript component itself. The modified text should be displayed in the textbox ...

Ensure that an HTTP post request is successfully completed before proceeding to execute the next HTTP post request within a loop

I have a loop that sends a HTTP post request each time it iterates. for(let i = 1; i < this.data.length; i++) { let arr = this.data[i]; this.http.post('link here', { name: arr[0], gender: arr[1], course: ar ...

Transform a row in an ng Smart table to a routerlink using Angular 2

I've been exploring ng2 Smart Table and I'm looking to convert a row (or even cell data) into a clickable link using routerlink. The current method I'm employing to retrieve some of my row's data is as follows: onUserRowSelect(event) ...

Implementing Ionic Native Player for Practical Applications

Looking for a way to incorporate a lightweight mp3 file into my Ionic App, I decided to utilize Native Audio from Ionic. Despite my best efforts, the solution did not function properly on the iOS emulator when called from /MyIonicApp/src/pages/home/home.ts ...