Confirming changes to checkbox values in Angular 2 prior to updating

My current challenge involves implementing a confirmation dialog in my application, and I'm feeling a bit unsure about the logic behind it.

UserDetailsComponent.ts

import { Component, OnInit, OnDestroy, ViewChild, Input, OnChanges, SimpleChange  } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ModalDirective } from 'ng2-bootstrap/modal/modal.component';

import { ApiService } from '../../assets/services/api.service';

import { UserDetails } from '../../assets/classes/controller-details';

@Component({
  selector: 'app-user-details',
  templateUrl: './user-details.component.html',
  styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit, OnDestroy, OnChanges {

    @Input('cmd') cmd_s: boolean;
    changeLog: string[] = []

    userDetailForm: FormGroup; 

    id: any;
    data: UserDetails = new UserDetails();

    submitted = false;
    active = false;

    private sub: any;

    constructor(
      private route: ActivatedRoute,
      private apiService: ApiService,
      private fb: FormBuilder) {}

    ngOnInit() {
      this.sub = this.route.params.subscribe(params =>{
        this.id = params['id']; //console.log(this.id);
        this.getData(this.id);
      })
    }

    ngOnDestroy(){
      this.sub.unsubscribe();
    }

    confirmDialog(e){
      if(e.target.checked){
        console.log('changing to on');
        this.active = true;
      }else{
        console.log('chenging to off');
        this.active = true;
      }
      this.active = false;
    }

    toOn(){
      this.controllerDetailForm.controls['status'].setValue(1);
      console.log('Changed to on');
    }

    toOff(){
      this.controllerDetailForm.controls['status'].setValue(0);
      console.log('Changed to off');
    }

    createForm(){
      this.controllerDetailForm = this.fb.group({
        id: [this.data.id],
        name: [this.data.name, Validators.required],
        status: [this.data.status, ]
      });
    }
}

I've created three functions confirmationDialog(), toOn(), toOff() to handle value manipulations before and after changes. While I initially thought these would help me accomplish the task, I now realize that something isn't quite right.

Below is my modal.

Modal

<input type="checkbox" #status formControlName="status" class="switch-input" [checked]="data.status" (change)="confirmDialog($event)">

<div bsModal #smallModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Confirmation</h4>   
                <button type="button" class="close" (click)="smallModal.hide()" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form class="form-horizontal">
                <div class="modal-body">
                    <p>Are you sure you want to change?</p>    
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary" value="Yes" (click)="onConfirmation() ">
                    <button type="button" class="btn btn-secondary" (click)="smallModal.hide()">No</button>
                </div>
            </form>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

For instance, when the current status is On, the confirmation dialog should have:

  • A 'Yes' button to change it to off
  • A 'No' button to revert/prevent the changes

What's the recommended way to implement a confirmation dialog for changing a radio button?

Any assistance would be greatly appreciated. Thank you in advance!

Answer №1

It seems that in your specific case, the change event is delayed because the status and ngModel of the checkbox have already been modified. To address this, you can utilize (click) to handle the confirmation aspect.

To prevent the checkbox's status from changing during the (click) event, you can use $event.preventDefault().

I have created a basic plunker example which employs window.confirm to display a confirmation dialog.

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

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Dealing with Typescript (at-loader) compilation issues within a WebPack environment

Currently, I am using Visual Studio 2017 for writing an Angular SPA, but I rely on WebPack to run it. The current setup involves VS building the Typescript into JS, which is then utilized by WebPack to create the build artifact. However, I am looking to t ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with: https://i.stack.imgur.com/4M54x.png whenever I attempt to update the view using *ngIf to toggle on an icon display. This is what my .ts file looks like: @Component({ selector: 'app-orders&ap ...

A guide on how to follow a specific item in an Angular 2 store

I have integrated ngrx store into my Angular2 application. The store reducer contains two objects as shown below: export function loadSuccessNamesAction(state: StoreData, action: loadSuccessNamesAction): StoreData { const namesDataState = Object.assi ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

Managing errors in ErrorHandler and addressing them in HttpInterceptor

Can you explain the difference between error handling methods in Angular 7? Is it necessary to handle global errors in HttpInterceptor and also in Angular's built-in ErrorHandler? In the HttpInterceptor, what types of errors can be handled, and in the ...

Developing a universal SDK wrapper for Firebase services (Firestore, Cloud Storage, and additional functionalities)

Currently, I am on the quest to discover an abstraction that can facilitate the seamless operation of Firebase products (specifically Firestore, Storage, and Analytics) across any platform (be it React Native, React, or Node.js). While considering the REST ...

Make TextField with type number forcibly show dot as decimal separator

I am currently utilizing the material-ui library to display a TextField component in my react application. Strangely, all instances of <TextField type="number /> are displaying decimal separators as commas (,) instead of dots (.), causing confusion f ...

`The form input status color remains static and does not update`

I encountered a situation in one of my projects where I need to visually indicate if a field is correct or incorrect based on the value of another field. To better illustrate this issue, I have created an example here. The main challenge: I am struggling ...

How can I delete the black background from the ion-tab-bar in Ionic 7?

In my current project using Ionic 7, I have a navigation guide set up with 4 tabs. I am trying to customize the styling of these ion tabs by adding some custom CSS. The issue I'm facing is that despite my attempts to make the background transparent, ...

What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application. While ngrx all ...

It appears that tsc is failing to recognize the "exclude" directives specified in the tsconfig.json file

I'm having difficulty with tsc recognizing my tsconfig.json file and compiling my .ts files. I keep encountering duplication errors that I'm trying to prevent using my tsconfig.json. Here's what I have: package.json tsconfig.json typings.j ...

Exploring StickIt: Binding the length property from a backbone.Collection

Exploring the use of Backbone, Marionette (1.8.3), StickIt, and TypeScript to effectively bind the length of a Backbone collection in real-time as items are added or removed. As someone new to StickIt, here's my current attempt: export class SomeVie ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Unable to assign a value to an undefined property in TypeScript

I need to store data in an object and then add it to another object let globalSamples = {} as any; let sample = { } as ISamplesDetail []; sample = []; for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++) { sample [i].id= thi ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

Using TypeScript to import npm modules that are scoped but do not have the scope name included

We currently have private NPM packages that are stored in npmjs' private repository. Let's say scope name : @scope private package name: private-package When we install this specific NPM package using npm install @scope/private-package It ge ...

"Discovering the root cause of Angular memory leaks and resolving them effectively is crucial for

I am facing an issue with a code that appears to be leaking, and I am seeking advice on how to identify the cause or properly unsubscribe. Even after adding an array containing all object subscriptions, the memory leakage persists. import { Component, On ...