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

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

Visual Studio Code encountering an NPM error

I am encountering errors when I try to run Visual Studio. The specific errors are: npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'F:\AngularNew\package.json' ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

When running the npm install command for Angular, an error occurred stating: "npm ERR! Maximum call stack

Upon running npm install, I encountered the following message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2256510f514b4f524e470f4351566213100c160c12">[email protected]</a>: NOTICE: ts-si ...

Angular application's HTML Canvas unexpectedly changes to a black color when I begin drawing

Currently, I am developing an Angular application in which users can draw text fields on PDF pages. To achieve this functionality, I have integrated the ng2-pdf-viewer library and created a PDF page component that incorporates an HTML canvas element. Howe ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...

Receive notifications from a JSON URL in your area

In my Ionic app, I have integrated a feature to display flight schedules using a JSON data API. The goal is to notify users through a bell icon about the status of the flight, whether it's arrival, delay, or landed. To achieve this, I have installed L ...

What steps should I follow to include Sass compilation in my Angular CLI 6 project in the angular.json file?

I recently started working on a project in Angular using the latest version of Angular CLI 6.0. However, I need to enable Sass compilation for my existing project. Typically, you can specify this during project creation, but since mine is already set up wi ...

Leveraging the angular-in-memory-web-api in conjunction with Angular CLI

Encountering some frustrating issues while trying to integrate angular-in-memory-web-api into my Angular 2 project that was built using Angular CLI. Here's the current structure of dependencies inside my package.json: "dependencies": { "@angular/co ...

Struggling to grasp the concept of Observable Catch closure scope in Angular2?

Seeking guidance on using catch with Observables. I find myself confused and would appreciate some assistance. My goal is to handle a 403 error from the API by deleting the local token and marking the user as unauthenticated in my TokenStore. The approach ...

Tips for initializing Cytoscape using Typescript

I developed a React component using Typescript that utilizes cytoscape (along with its typings) as a headless model. My goal is to turn this into an NPM package so it can be easily imported into other projects. About my library: It functions correctly wh ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Encountering "environment.prod.ts path does not exist in file replacements" error while Dockerizing Angular build

I am encountering an issue with a Dockerfile that throws an error during the build process. I attempted to install the angular/cli globally and run ng build --prod using a separate RUN command, but the same error persists. Dockerfile FROM node:12.17.0-al ...

Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators. Here is our old code snippet: const ADD_NAME = 'ADD_NAME'; /** * Se ...

Using Rails 5 API to generate a new object using JSON with nested resources

Here is the JSON data that was received as parameters from an external Angular web app: { "provincia": { "id": 1, "name": "Province" }, "username": "tester", "direccion": "new avenue 100", "email": "<a href="/cdn-cgi/l/email-protectio ...

"Encountering a 404 Error when attempting to refresh an Angular 13 application hosted on an Apache

I have developed a prototype web application and now need to deploy it on an Apache server running Ubuntu OS. After building the web app, I hosted it on my local machine for testing purposes. I have configured the .htaccess file as follows: RewriteEngine ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

Typescript is failing to pick up process.env variables and is treating them as undefined, even though they are

I thought that by adding environment variables to environment.d.ts, they would have the correct types. I am using @types/node as a dev-dependency, and I have defined DATABASE_URL in my environment.d.ts like this: declare global { namespace NodeJS { ...

Is the async pipe automatically unsubscribing from an observable that is defined in a service and referenced in a component variable?

Within my service, I have a BehaviourSubject declared and I reference it with a variable in another component. In the view of that component, I subscribe to the subject using the said variable, as shown below: Service: public exampleSubjebt$ = new Behavi ...

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...