"Using MatCheckbox's preventDefault() method to access the checked value of the

Is there a way to customize a Material checkbox to prevent it from being checked or unchecked by default (e.g., by calling preventDefault() on the event) and still retrieve the checked value from the event?

It appears that achieving both conditions simultaneously is challenging. When using the (click) event, retrieving the checkbox's value seems impossible, while with the (change) event, preventing the default checkbox value change becomes tricky (one would prefer to change the checkbox value only after a successful underlying HTTP request).

Find the Stackblitz example here: https://stackblitz.com/edit/matcheckbox-checked

<mat-checkbox 
  [checked]="checked"   
  (click)="onClick($event)"
>Click me!</mat-checkbox>

<br/>

<mat-checkbox 
  [checked]="checked"
  (change)="onChange($event); false"
>Change me!</mat-checkbox>

export class CheckboxOverviewExample {
  checked: boolean = false;

  onClick(event) {
    event.preventDefault();
    console.log('onClick event.checked ' + event.checked);
    console.log('onClick event.target.checked '+event.target.checked);
  }

  onChange(event) {
    // Unable to use event.preventDefault();
    console.log('onChange event.checked '+event.checked);
  }
}

The (click) event produces undefined values but successfully halts event propagation, while the (change) event retrieves the value but allows event propagation.

Check out related issues here:

Answer №1

To block the default action on the "change" event, you can utilize a provider within the component:

providers: [{
    provide: MAT_CHECKBOX_DEFAULT_OPTIONS, 
    useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions
}]

(source: https://material.angular.io/components/checkbox/overview#noop)

You can then link the checked status to a local variable (or a getter function)

<mat-checkbox
(click)="changeValue()"
[checked]="theValue"
>
   Whatever
</mat-checkbox>

Therefore, in the code, for instance, you can use theValue as the value and update it programmatically. This approach eliminates the need to pass the checkbox state as an argument to the click method; you can access it directly from theValue.

theValue: boolean = false;

changeValue(): void {
    this.theValue = !this.theValue
}

Answer №2

When it comes to coding for accessibility, I have encountered a scenario where I needed to handle both mouse and keyboard events. Simply relying on a click event was not sufficient as I also had to consider key presses like 'Space'. Additionally, after resolving the Space key issue, I realized that it was interfering with keyboard navigation using the Tab key. This required me to make some adjustments to the code.

      <mat-checkbox [checked]="descendantsAllSelected(node)" 
        [indeterminate]="descendantsPartiallySelected(node)"
        (click)="toggleDescendants(node,$event)"
        (keydown)="toggleDescendants(node,$event)"
        >
        {{node.name}}
      </mat-checkbox>

In the code snippet above, I implemented a function called toggleDescendants to manage both mouse and keyboard events. It ensures proper handling of events and prevents unwanted actions when navigating using the Tab key.

  toggleDescendants(node, $event) {
    this._logger.debug('toggleDescendants()');
    this.treeControl.toggleDescendants(node);
    if ($event.code !== 'Tab') {
      $event.preventDefault();
    }
  }

Answer №4

attempt indefinite

verify
Switch the checked status of the checkbox, disregarding the indeterminate value. If the checkbox is in an indeterminate state, it will still appear as an indeterminate checkbox regardless of the checked status.

confirm-indeterminate
The standard behavior of mat-checkbox. Resets the indeterminate state to false whenever the user clicks on the mat-checkbox. This mirrors the behavior of a native "input type="checkbox".

https://material.angular.io/components/checkbox/overview#-code-check-code-

Answer №5

Managing the default actions of checkboxes and event attributes is beyond our control. A possible solution could involve using two image icons that represent the checked and unchecked states, and toggling them accordingly depending on the value.

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

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Having trouble pinpointing the specific custom exception type when using the throw statement in TypeScript?

I have run into a problem while using a customized HttpException class in TypeScript. Let me show you how the class is structured: class HttpException extends Error { public status: number | undefined; public message: string; public data: any; ...

Generating instances using TypeScript generics

Looking to create a factory for instantiating classes with generics. After checking out the TypeScript docs, everything seems to work as expected. Here's a simplified version of how it can be done: class Person { firstName = 'John'; ...

How to Import External Libraries into Angular 2

I am attempting to import a 3rd party library called synaptic. This library is written in JavaScript and I have a .d.ts file for it. Here are the steps I have taken: npm install synaptic --save npm install @types/synaptic --save I have also added the fol ...

A <mat-card> does not have a raised appearance because it lacks a border

Looking for help with my HTML code. Here's the setup: <mat-card> <mat-card-content> <code>{{file}}</code> </mat-card-content> </mat-card> But when the mat-card element is rendered, it's not ra ...

What is the best way to design functions that can return a combination of explicit types and implicit types?

When looking at the code provided below, function system(): ISavable & ISerializable { return { num: 1, // error! save() {}, load() {}, serialize() {}, deserialize() {}, } } interface ISavable { sa ...

Achieving intellisense functionality in TypeScript without the use of classes

Just dipped my toes into TypeScript, attempting to convert this basic JavaScript code to TypeScript. Here is the JavaScript code snippet: Item = {} Item.buy = function (id) {} Item.sell = function (id) {} I prefer not to use classes and would like to ut ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Event vs ViewChild: Understanding the best way for parent components to obtain information from child

My situation involves multiple basic form components that need validation in the parent component. To achieve this, I must pass formGroups from the child components to the parent. The question is, what is the preferred method for passing a formGroup from a ...

The deno bundle operation failed due to the absence of the 'getIterator' property on the type 'ReadableStream<R>'

When attempting to run deno with bundle, an error is encountered: error: TS2339 [ERROR]: Property 'getIterator' does not exist on type 'ReadableStream<R>'. return res.readable.getIterator(); ~~~~~~~~~~~ ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Incorporate numerous values into the disabled attribute within an Angular application

Currently, I am attempting to include values in a disabled directive. In the code snippet below, you can see that I have disabled a button if a value matches System Admin. Now, my goal is to add additional values to this condition. Specifically, I would li ...

Incorrect typings being output by rxjs map

combineLatest([of(1), of('test')]).pipe( map(([myNumber, myString]) => { return [myNumber, myString]; }), map(([myNewNumber, myNewString]) => { const test = myNewString.length; }) ); Property 'length' does not ...

Issue with displaying Angular index.html page post-build

My Angular application runs smoothly on ng serve, but after building and uploading with ng build --prod, the index.html file fails to open. I've tried using various base href configurations like <base href="#">, <base href="/& ...

Encountering difficulties in loading environment variables while starting the server using typescript in combination with node.js

My node.js server project, created using typescript, has the following structure: |--node_modules |--server .env |-- build |-- src |-- database |-- controllers |-- models |-- routes |-- utils |-- app. ...

Rearranging data received from an Observable

TL;DR I am working on an Angular app where I need to shuffle an array of names retrieved from a network request and ensure that each group of 6 names selected is unique. However, I noticed duplicates in the selections. Here's a CodePen example using o ...

In TypeScript, what specific term denotes a type of data?

Given the following code snippet: class Foo { } interface TypeProvider() { type(): ?; } class Bar implements TypeProvider { type(): ? { return (Foo); } } class Baz implements TypeProvider { type(): ? { return (Bar); ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

Executing React's useEffect hook twice

As I work on developing an API using express.js, I have implemented an authentication system utilizing JWT tokens for generating refresh and access tokens. During testing with Jest, Supertest, and Postman, everything appears to be functioning correctly. O ...

Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far: function customFunction<T = any>(input ...