(change) fails to function properly if the "Select All" checkbox is used to select all checkboxes

Angular 4 is the framework I am working with, and I have a series of checkboxes generated within a loop. When I individually click on them, the (change) function works as expected. However, when I try to use the select all checkbox, it does not trigger the change event on the individual checkbox inputs.

I have set the value of each input to sc.id. My intention was to add them to an array whenever the (change) event occurred, but this does not work when I choose select all.

If anyone can point out what I am doing wrong or has a better suggestion, please share your insights.

Sample HTML Code:

<input type="checkbox" class="custom-control-input"  (change)="allSelected = !allSelected">

<div *ngFor="let sc of scs?.data">
    <input type="checkbox" class="custom-control-input" [value]="sc.id" [checked]="allSelected" (change)="onSCSelect($event)">
</div>

Sample Component Code:

allSelected = false;

onSCSelect(event) {
    console.log(event);
}

To recreate the issue, I have created a Plunker: https://embed.plnkr.co/TFxziXAEeutvLZ5rUXZS/

Answer №1

To achieve the desired outcome, it is recommended to utilize [(ngModel)].

HTML Code

    select all
    <input type="checkbox" class="custom-control-input" [(ngModel)]="allSelected" (ngModelChange)="onAllSelectedChanged($event)">
    <br/>
    <div *ngFor="let sc of scs">
        <input type="checkbox" class="custom-control-input" [(ngModel)]="sc.checked" (ngModelChange)="onSelectionChanged($event)">
    </div>

TS Code

export class AppComponent {
  allSelected = false;
  scs = [
    {id: 1},
    {id: 2},
    {id: 4}
  ];

  onAllSelectedChanged($event) {
     for(let i=0; i<this.scs.length; i++) {
       this.scs[i].checked = this.allSelected;
     }
  }

  onSelectionChanged(isSelected) {
   if (!isSelected) {
     this.allSelected = false;
   }
  }
}

Refer to the updated plunker below for more information:

https://plnkr.co/edit/uSsI5YnBYShyIykAI7Vs?p=preview

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

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Why isn't Nodemon monitoring the directory in webpack-typescript-node.js?

Here are the contents of the package.json file for a TypeScript project using webpack and node.js: "scripts": { "build": "webpack", "dev:start": "nodemon --watch src --exec \"node -r dotenv/co ...

Troubleshooting an Angular application

Just diving into Angular and following along with the tutorial on https://angular.io/tutorial. However, I seem to be facing an issue in Chrome where the const HEROES is not available in my watch list. It keeps showing as "not available". What could be ca ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

The build process is encountering issues with lodash causing npm to fail

Utilizing Node: 16.20.2 Angular: CLI 11.2.5 Typescript: 4.1.5 @types/lodash: 4.14.177 An issue has arisen where the npm build process is failing with the following exception: Error: node modules/@types/lodash/common/object.d.ts:1026:46 error TS1 ...

What is the proper way to refactor this TypeScript class?

Can you assist me in converting this class into TypeScript and explaining why it's not functioning? class Students { public name: string; public surname: string; public age: number; } constructor(name:string,surname:string,age:number) { ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

The intersection observer is unable to track multiple references simultaneously

Hey there, I've been using a switch statement in my Next.js project to dynamically serve different components on a page. The switch statement processes a payload and determines which component to display based on that. These components are imported dy ...

Can we break down and explain iterative dynamic imports with conditions in JavaScript?

Is there a way to simplify the named imports and assignments in my code programmatically without repeating myself? I am looking for a solution that involves using a loop. This is what I currently have: import { globalLocale } from './i18n' let ...

Executing a method with parameters in ngOnInit in Angular - A simple guide

Is it feasible to trigger a parametrized method in ngOnInit within the same component? I currently have an onclick(p.key) function in the html file, defined in the corresponding typescript file. However, my aim is to invoke it during ngOnInit. Is this achi ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Exploring the capabilities of AngularJS2's formGroup and formControlName functionality

Exploring the world of AngularJS2, I recently created a sign-up page utilizing formGroup formControlName, but encountered an issue with passing null values to the object. HTML code: <div class="col-md-8 col-md-offset-2"> <form [formGroup]="m ...

HttpClient experiences a timeout in processing the request

Currently, I am utilizing TypeScript in conjunction with ASP.NET Core Web API. Situation: I am facing a challenge with a backend data response service that is taking more than two minutes to load the data. It appears that the default timeout for the Http ...

When using <a> with routerLink and fragment, the focus is not automatically set on the element

Struggling with meeting WCAG standards for page navigation in Angular 9.0.6. This is how my app-component is structured: <nav class="pageNav"> <ul> <li><a [routerLink]="" fragment="main-nav">Navigation</a></li> ...

What causes the variable to be undefined in the method but not in the constructor in Typescript?

I am currently working on an application using AngularJS 1.4.9 with Typescript. In one of my controllers, I have injected the testManagementService service. The issue I'm facing is that while the testManagementService variable is defined as an object ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

Best practices for incorporating JavaScript into Angular applications

I am looking to integrate a JavaScript library into my Angular application. After researching various methods, I have decided to incorporate the library found at . I was hoping to create a module named 'plot-function' that would offer a function ...

Struggling to locate the ID linked to a specific ObjectId and encountering issues with the import function?

Can someone help me with this issue? Error Message: ERROR TypeError: answerID.equals is not a function I am unsure why I am getting this error. Here is the code snippet: import { ObjectId } from 'bson'; export class Person{ personID: Objec ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...