What could be causing the TypeError in Angular when utilizing '$event.target.checked' with mat-checkbox?

While working with Angular mat-checkbox, I encountered an error when trying to use $event.target.checked. The error message stated - "Cannot read property 'checked' of undefined at Object.eval [as handleEvent]". This issue arose while attempting to pass multiple values for a checkbox in Angular8.

onChange(cls: string, isChecked: boolean) {
  const clsFormArray = < FormArray > this.myForm.controls.usercls;
  if (isChecked) {
    clsFormArray.push(new FormControl(cls));
  } else {
    let index = clsFormArray.controls.findIndex(x => x.value == cls);
    clsFormArray.removeAt(index);
  }

}
<mat-checkbox class="example-margin" (change)="onChange(data.cls, $event.target.checked)">
  {{ data.cls }}
</mat-checkbox>

<mat-checkbox class="example-margin"(change)="onChange(data.cls,$event.target.checked)">
{{ data.cls }}
</mat-checkbox>
    onChange(cls: string, isChecked: boolean) {
            const clsFormArray = <FormArray>this.myForm.controls.usercls;
            if (isChecked) {
              clsFormArray.push(new FormControl(cls));
            } else {
              let index = clsFormArray.controls.findIndex(x => x.value == cls);
              clsFormArray.removeAt(index);
            }
            }

I am hopeful that the classes will be successfully pushed and added to the array so that I can print them.

Answer №1

You can simplify the code by sending only $event.checked instead of target. Here is the revised version:

<mat-checkbox class="example-margin" (change)="onChange(data.cls, $event.checked)">
  {{ data.cls }}
</mat-checkbox>

Answer №2

<div class="custom-checkbox"(change)="handleCheckboxChange($event)">
{{ data.cls }}
</div>

  handleCheckboxChange(event) {
            const clsFormArray = <FormArray>this.myForm.controls.usercls;
            if (event.checked) {
              clsFormArray.push(new FormControl(event.source.value));
            } else {
              let index = clsFormArray.controls.findIndex(x => x.value == event.source.value);
              clsFormArray.removeAt(index);
            }
            }

Answer №3

Replace $event.source.value with the source instead of target. If using source doesn't solve the issue, you can examine your web application in your browser to identify the object name and substitute that name for target.

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 have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Vue.js failing to receive mandatory prop

Starting with Vue.js is exciting, but there may be some obvious things that I'm missing out on. As a practice exercise, I attempted to create a simple treeView component (with a subcomponent 'treeViewItem'). The only property in the treeView ...

Using Angular to dynamically modify the names of class members

I am working with an Angular typescript file and I have a constant defined as follows: const baseMaps = { Map: "test 1", Satellite: "test 2" }; Now, I want to set the member names "Map" and "Satellite" dynam ...

Switch between every other pair of table rows, then repeat with the following two pairs

I am attempting to create a table with alternating row colors of green and yellow in sets of two. I have been using :nth-child but it is not working correctly. My table is automated using Angular 6 and styled with Angular Material 6. If you would like to ...

Ensure that the height of the ngx-treeview matches the size of the browser window and adjusts dynamically as the browser size

config = TreeviewConfig.create({ hasAllCheckBox: false, hasFilter: true, hasCollapseExpand: false, decoupleChildFromParent: false, maxHeight: 600 }); **I am currently working on creating a responsive ngx-treeview where the height adjusts based on the brow ...

Some of the compiler options that are not commonly known are those for including and

Embarking on my first typescript-node-express project, I decided to create my own tsconfig file with the following configuration: { "compilerOptions": { "target": "es6", "module": "commonjs", "strict": true, "baseUrl": "./", "outDi ...

Is it advisable to include JavaScript files produced by TypeScript in the gitignore when creating a library?

As I develop my library, my TypeScript files reside in the src directory. To streamline the process, I have set up the tsc compiler to generate JavaScript files in a separate js folder, with the final bundled scripts stored in a dist folder. Considering t ...

How can we use Angular Table to automatically shift focus to the next row after we input a value in the last cell of the current row and press the Enter key

When the last cell of the first row is completed, the focus should move to the next row if there are no more cells in the current row. <!-- HTML file--> <tbody> <tr *ngFor="let row of rows;let i=index;" [c ...

Encountering issues with loading resources within the Angular production environment

Currently, I am in the process of deploying an Angular-CLI app onto a server. After using the command ng build --environment=production, the build was successful without encountering any errors. Subsequently, running the ng serve command did not throw any ...

Exploring the world of Polymer's Paper Elements and Angular Material

I need assistance in deciphering these quotes from the Angular Material GitHub and official website: It should be noted that this project is still in its early pre-release stage. Angular Material serves as a reference implementation of Material Design whi ...

Error: Unexpected character < in node_modules/angular2/ts/package.json syntax

I am currently working on developing an app with Angular 2 and have encountered an error during setup. The error message I received is: SyntaxError: /home/mts/Desktop/sampleProject/appSails/node_modules/angular2/ts/package.json: Unexpected token < at O ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

webpack 2 does not support absolute paths

I have been facing challenges implementing absolute paths with webpack 2 in my angular 2 project. I decided to start from scratch using this as a reference codebase. To enable absolute paths, I made the following changes in my webpack.config.ts: config.r ...

Having trouble applying CSS styling to the div element

I'm new to CSS and struggling with aligning content within a div. Specifically, I can't get the actual price (striked off) to display next to the discounted price in the card - it keeps appearing underneath. Any ideas on how I can improve my CSS ...

The bindings of Angular 2 input properties are not functioning as expected

Creating a component to encapsulate a Google Map is my ultimate goal. Google Maps objects offer numerous options to configure. In Angular1, I utilized attributes to construct map object options. Transitioning to Angular2, my approach involves leveraging ...

Is Error k originating from Angular or Electron?

While utilizing Angular 10 in my Electron application, I encountered some errors after building a release version of the app. These errors are visible in the Chrome Inspector, but it's unclear whether they stem from Electron or Angular, and the messag ...

Show a select element with choices that change depending on another select element

I am currently working on a select dropdown component that utilizes the @Input option variable. My goal is to have another instance of this component display options based on the selection made in the first instance. Any suggestions on how to make this h ...

Deployment failure due to undetected development keys in gitignore

I have a TypeScript-coded Express server with three files for keys in the compiled and pre-compiled code: /// dev.ts - development keys const keys = { googleClientSecret: "GOOGLE_KEY", mongoURI: "mongodb+srv://MONGO_K ...

Tips for creating a standard function that accepts only one type

It seems like I might be overlooking something, but is it possible to define a function with just one existing type? Check out the sandbox. type Fn = (x: number) => boolean // this cannot be changed const arrowFn: Fn = (x) => { return !x } // I ...

Transforming JSON data into an HTML template

Incorporating Angular 6 in my project, I have come up with the following templates: Header, Left panel, Body part, Footer Header, Left panel, Body part, Right panel, Footer Header, Body part, Footer Considering the numerous templates, I am aiming to tran ...