The status of the Mat-checkbox is determined by the response from the modal dialog

In my project, I have a list of users stored in an array. Using HTML, I utilized the *ngFor directive to create a checkbox for each user element. Additionally, there is an @Input assignedAccountIds[] which contains the IDs of default selected users.

The code snippet for the checkbox element looks like this:

<mat-checkbox
   color="primary"
   [disabled]="disableCurrentAccountCheckbox && account.id === currentAccountId"
   [checked]="isAccountSelected(account)"
   (change)="onSelectAccount($event, account)"
>

The method isAccountSelected determines whether a user is included in the selected items array to decide if the checkbox should be checked or not. Here is its implementation:

isAccountSelected(account: ClientAccount): boolean {
    return (this.assignedAccountIds || []).includes(account.id);
}

When the change event occurs, the onSelectAccount method handles it as shown below:

onSelectAccount(event: MatCheckboxChange, account: ClientAccount): void {
    if (
      !event.checked &&
      this.currentAccountId &&
      account.id === this.currentAccountId
    ) {
      const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
        data: {
          message: `You will not be able to see this inspection if you unassign yourself!`,
          buttonColor: 'primary',
          buttonLabel: 'Unassign',
        },
        position: {
          right: '10px',
          bottom: '10px',
        },
        maxWidth: '580px',
      });

      dialogRef
        .afterClosed()
        .pipe(untilDestroyed(this))
        .subscribe(result => console.log(result));
    } else {
      this.selectionChange.emit({ id: account.id, checked: event.checked });
    }
  }

Essentially, I am implementing a feature that triggers a confirmation modal when a user attempts to unselect themselves from the list. The checkbox state will only change based on the user's selection (Yes/No) in the modal dialogue.

Answer №1

MatCheckbox does not have a built-in feature to intercept a check/uncheck action directly. The only option is to listen for the change event after it occurs. However, you can utilize a regular click event to achieve interception:

Intercepting Checkbox Clicks

<mat-checkbox #cb (click)="confirmAssign($event)">Assigned</mat-checkbox>

Dialog Button Actions

<mat-dialog-actions>
  <button mat-button [mat-dialog-close]="false">Cancel</button>
  <button mat-button [mat-dialog-close]="true">Unassign</button>
</mat-dialog-actions>

TypeScript Code

@ViewChild('cb', {static: true}) cb: MatCheckbox;

constructor(public dialog: MatDialog) {}

confirmAssign(event) {

  // Intercept only when checkbox is currently checked
  if (this.cb.checked) {

    // Prevent the checkbox from being unchecked by default click behavior
    event.preventDefault();

    // Ask for confirmation through a dialog 
    this.dialog.open(ConfirmationDialogComponent).afterClosed().subscribe(confirmed => {
      if (confirmed) {
        // Uncheck the checkbox after confirmation
        setTimeout(() => this.cb.checked = false);
      }
    });
  }
}

Answer №2

One effective method I have discovered in version 15 is to create a custom 'noop' MAT_CHECKBOX_DEFAULT_OPTIONS to modify the default click action:

Component:

@Component({
    selector: 'app-checkbox-component',
    templateUrl: './app-checkbox.component.html',
    styleUrls: ['./app-checkbox.component.scss'],
    providers: [
        { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions },
    ],
})
export class InlineHardCopyDeliveredEventComponent {
    isCheckboxChecked = false;

    constructor(private dialog: MatDialog) {}

    openModal(): void {
        this.dialog
            .open()
            .afterClosed()
            .subscribe((result) => {
                this.isCheckboxChecked = result;
            });
    }
}

Template

<mat-checkbox
    (click)="openModal()"
    [checked]="isCheckboxChecked"
></mat-checkbox>

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

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

Filtering an array of objects in TypeScript based on the existence of a specific property

I'm attempting to filter objects based on whether or not they have a specific property. For example: objectArray = [{a: "", b: ""}, {a: ""}] objectArray.filter( obj => "b" in obj ).forEach(obj => console. ...

An in-depth guide on implementing Highcharts.Tooltip functionality in a TypeScript environment

Currently, I am trying to implement a tooltip activation on click event in Highcharts by following an example from this URL: Highcharts - Show tooltip on points click instead mouseover. The challenge I'm facing is that I am using TypeScript and strugg ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Identical values within an array property of an object

I'm completely new to working with Angular and I'm hoping someone can offer some guidance. Currently, I have a component with an object array as a property. The issue arises when I update this array with a new object, as all the items in the arr ...

Merging identical values from an array in Angular to create a unified object

Here is an array I'm working with: data = [{ name: 'Camilla', date: '00.08.1990' }, { name: 'John', date: '10.06.2022' }, { name: 'Paul', date: '10.06.2022' ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Divide the firestore request into multiple filters

I am currently developing a filter system that allows users to search for specific parameters without filling out the entire form. For instance, they could search for games of a certain type but across all genres (leaving the form empty results in an empty ...

Align the checkbox input in the center of a flexbox container

I am in the process of creating a side menu with filters, and I need to design a row that includes an input checkbox along with some accompanying text. However, I am facing an issue where the checkbox does not center properly within the flex container when ...

Can ES6 class getters, setters, and private properties be utilized in TypeScript with an interface?

I'm currently using TypeScript and trying to figure out how to implement an interface in a class that utilizes ES6 getters and setters. Is it even possible? When I use the code below, errors are highlighted in the class. For instance: (property) S ...

Cross-Origin Resource Sharing problem with identical URL

I encountered a CORS issue with my Angular 6 application running on port 4200 and using an API on port 3000. To address this, I implemented the following code snippet on the server side: app.use(function(req, res, next) { res.header("Access-Control-Allo ...

Tips for maintaining the data type of a typed array in typescript while clearing it?

During a recent class, I defined an array with the type CustomType as shown below: class Example { public exampleArray: CustomType[]; public clearArray() { this.exampleArray = []; } } It appears that the clearArray method assigns an UNDEFINED t ...

The callback function does not seem to work when using MUI v4 PropFunc

Encountering an issue with custom styling using PropFunc in Material UI (MUI) v4 (4.12.4). When providing a PropFunc in the traditional callback way to get CSS, it works as expected: const useStyles = makeStyles((theme) => { return { input: { ...

Angular 2 encountering an error: "@types module is missing"

After dedicating an excessive amount of time to this issue, I am finally surrendering. The challenge lies in incorporating a module into my angular 2 project: import * as d3ScaleChromatic from 'd3-scale-chromatic'; Unfortunately, this results ...

Material Modules are causing issues with AOT compilation

I'm encountering multiple errors that all share a similar pattern: ERROR in ./node_modules/@angular/material/button/typings/index.ngfactory.js Module build failed: Error: Invalid name: "@angular/material/button" at ensureValidName (C:\path&b ...

When using the ":enter" query in Angular animations builder, it resulted in no elements being returned

Currently, I have implemented animations for child elements using AnimationBuilder and AnimationPlayer, along with the query function. However, I encountered an issue where the animation stopped working when I tried to use :enter in the query. private cr ...

Various hues blending and intertwining with one another

https://i.stack.imgur.com/zLrNK.png Could someone please clarify what is happening here? I'm attempting to change the background color to dodgerblue, but for some reason, the white background color is still showing through. Below is the code snippet ...

Encountered an issue in Angular 2 when the property 'then' was not found on type 'Subscription'

I have been attempting to call a service from my login.ts file but I am encountering various errors. Here is the code snippet in question: login.ts import { Component } from '@angular/core'; import { Auth, User } from '@ionic/cloud-angular ...

Continuously verify if there are any active child elements

I am dealing with a recursive list of items in Angular/TypeScript. My goal is to only show items when they are either active=true; themselves or if any of their children or grandchildren are also active=true. data.json [ { "active": ...

What are the steps to configure JSS in a TypeScript/NextJS application?

Trying to set up a basic web app using React, TypeScript, NextJS, and Material-UI has been quite the challenge. The main issue I am facing revolves around styling within my project. To better illustrate my problem, I have created a CodeSandbox environment. ...