Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work.

Below is the list:

<td mat-cell *matCellDef="let element; let i = index">
 <div fxLayout="row" fxLayoutAlign="start start" [style.backgroundColor]="i.checked ? '#D4EBFF':''">
    <div fxFlex="1">
      <h2>{{element.position}}</h2>
    </div>
    <div fxLayout="column" fxLayoutAlign="space-between start" fxFlex="94">
      <ul class="imagelist-ul" (click)="listclick()">
        <li class="imagelist-label"><strong>{{element.label}}</strong></li>
        <li class="imagelist-totalincl"><strong>Total Inclusion:</strong> {{element.total_inclusion}}</li>
        <li class="imagelist-avg"><strong>Average Probability:</strong> {{element.avg_probability}}</li>
      </ul>
    </div>
    <div fxFlex="5" class="imagelist-chkbox">
        <mat-checkbox color="primary" #i (change)="!i['checked']"></mat-checkbox>
    </div>
  </div>
</td>

Any ideas on how this can be achieved would be appreciated.

Answer №1

To apply the ngClass based on your checkbox condition, include the following code in your ul list.

[ngClass]="{'isDisabled': !i.checked}"

Include the following class in your CSS file to disable pointer events: pointer-events: none.

.isDisabled {
    pointer-events: none;
    opacity: 0.5;
}

The final code would look like this:

<div fxLayout="row" fxLayoutAlign="start start" [style.backgroundColor]="i.checked ? '#D4EBFF':''">
    <div fxFlex="1">
      <h2>{{element.position}}</h2>
    </div>
    <div fxLayout="column" fxLayoutAlign="space-between start" fxFlex="94">
      <ul class="imagelist-ul" (click)="listclick()" [ngClass]="{'isDisabled': !i.checked}">
        <li class="imagelist-label"><strong>{{element.label}}</strong></li>
        <li class="imagelist-totalincl"><strong>Total Inclusion:</strong> {{element.total_inclusion}}</li>
        <li class="imagelist-avg"><strong>Average Probability:</strong> {{element.avg_probability}}</li>
      </ul>
    </div>
    <div fxFlex="5" class="imagelist-chkbox">
        <mat-checkbox color="primary" #i (change)="!i['checked']"></mat-checkbox>
    </div>
  </div>
</td>

Add the following code snippet to your CSS file as well:

.isDisabled {
    pointer-events: none;
    opacity: 0.5;
}

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

Create an instance of a class from a group of subclasses, all the while retaining the ability to access static members in Types

I seem to have encountered a dilemma where I am looking to have both the static and abstract keywords used for a member of an abstract class in TypeScript, but it appears that this combination is not supported. The nearest workaround I could come up with ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

Perplexed by the persistent failure of this Jasmine test accompanied by a vexing "timer in queue" error

I'm attempting to test a function that uses RxJS to broadcast long press events to subscribers. Below is the implementation of the function: export function watchForLongPress(target: HTMLElement) { let timer: number; const notifier = new Subject& ...

What is the correct way to construct this query?

I've been attempting to run this query with Sequelize but keep encountering an error Query LineItem.findAll( { attributes: [ "orderId", [fn("sum", col("quantity")), &qu ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

Converting JSON responses from Observables to Arrays of objects in Angular

I have created a custom interface called Table which defines the structure of my data. export interface Table { id: number; title: string; status: string; level: string; description: string; } In my service, I am using HttpClient to se ...

Steering clear of Unfulfilled Promises in TypeScript. The Discrepancy between Void and .catch:

When it comes to handling promises in TypeScript, I'm used to the then/catch style like this: .findById(id) .then((result: something | undefined) => result ?? dosomething(result)) .catch((error: any) => console.log(error)) However, I have also ...

Sending a POST request in Angular5 using the HTTP module

Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" locate ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Filtering Deno tests by filename: A step-by-step guide

How can I selectively run Deno tests based on their filenames? Consider the following test files: number_1_test.ts number_2_test.ts string_test.ts If I want to only run tests with filenames starting with number*, I am unable to use either of these comma ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Setting up data in Firebase can be challenging due to its complex structure definition

https://i.stack.imgur.com/iclx7.png UPDATE: In my firebase structure, I have made edits to the users collection by adding a special list called ListaFavorite. This list will contain all the favorite items that users add during their session. The issue I a ...

The onChange event does not work as expected for Select controls

I am facing an issue with my common useForm.tsx file when handling the onChange event for select controls. The error message I encounter is displayed below. Does anyone have any suggestions on how to resolve this? Error: Type '(e: ChangeEvent<HTM ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Using React Query's useMutation hook may result in an error message of "No overload matches this call"

When incorporating react-query into my typescript project, I encountered a perplexing type error while attempting to utilize the useMutation() hook with a graphql query. Here is an example of the code: useMutation( async ( parameter1: string, ...

What is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

The element type 'ReactElement<any>' does not match a JSX element constructor function. 'undefined' cannot be assigned to type 'Element | null'

After attempting the suggested fix of deleting node_modules/ and yarn.lock, then reinstalling everything, I still cannot resolve the issue. I am currently developing a basic router that renders children based on a certain prop: import React, { Fragment } ...

What is the proper way to utilize queries in BlitzJS?

I am attempting to extract data from a table by filtering based on the relationship with the Blitzjs framework. However, I am facing difficulties using queries as it seems to be the only option available. Every time I try to call the quer ...

An empty constant object can trigger an endless cycle of re-rendering

Consider this simplified scenario: export function myCustomHook<TData = Record<string,string>> (data?: TData) { const [output, setOutput] = useState<number>(); const customFunction(data?: TData) { //In a real scenario : p ...