Is there a way to ensure the switch only changes after I have clicked 'ok' to confirm?

Is there a way to ensure that the toggle switch only changes when I click "Ok" in the confirmation box? If I click "Cancel", I would like for nothing to change.

This is my HTML code:

<mat-card class="result">
  <mat-card-content>
    <h2 class="example-h2">Result</h2>
     <section class="example-section">
      <mat-slide-toggle
          class="example-margin"
          [color]="color"
          [checked]="checked"
          [disabled]="disabled"
          (click)="myfunction()">
        Slide me!
      </mat-slide-toggle>
    </section>
  </mat-card-content>
</mat-card>

And this is my TypeScript code:

export class SlideToggleConfigurableExample {
  color = 'accent';
  checked = false;
  disabled = false;
    myfunction() {
    if (confirm('Are you sure you want to change the status?')) {
     }
  }
}

I attempted the following approach:

<mat-slide-toggle
      class="example-margin"
      [color]="color"
      [checked]="checked"
      [disabled]="disabled"
      (click)="myfunction()"
      onclick="return confirm('Are you sure?')">
    Slide me!
  </mat-slide-toggle>

and removed

if (confirm('Are you sure you want to change the status?')) {}
from the TypeScript code.

With this, my function gets executed whether I click "ok" or "cancel".

Could someone please advise on how to make sure the switch only changes upon clicking "Ok"?

Thank you

Update:

Here is the updated HTML code:

<form [formGroup]="myform" class="col s12">
<div *ngFor="let item of homeboxsp;let i = index">
            <section class="example-section">
            <mat-slide-toggle value="active" formControlName="active-{{i}}" class="example-margin" [checked]="item.active === '1'"(click)="onActiveHomeboxP()"> {{item.active}}
            </mat-slide-toggle>
        </section>
</div>
</form>

And here is the TypeScript code:

export class AppComponent {
  public homeboxsp: HomeboxP[] = [];
  myform: FormGroup;
  checkedBtn: boolean;
  constructor(public service: Service) {
  }
  ngOnInit() {
    this.populateFormHomeboxP();
  }
  populateFormHomeboxP() {
    this.homeboxsp = this.service.getData();


    let controls = {
      'homeboxpackage_id': new FormControl('', Validators.required)
    };

    for (let i = 0; i < this.homeboxsp.length; i++) {
      controls['active-' + i] = new FormControl(this.homeboxsp[i].active == '1', Validators.required)
    }
    this.myform = new FormGroup(controls);
    this.patchForm();
  }
  patchForm() {
    this.myform.patchValue({
      homeboxpackage_id: this.homeboxsp.map(x => x.homeboxpackage_id),
    });
    console.log(this.homeboxsp.map(x => x.active))
    console.log(this.homeboxsp.map(x => x.homeboxpackage_id))
  }
  onActiveHomeboxP() {
    if (confirm('Are you sure?')) {
      let edigps = this.myform.value
      console.log(edigps)
      console.log('true')
    } else {
      this.checkedBtn = !this.checkedBtn;
    }
  }
}

Image: https://i.sstatic.net/ApLLv.png

  1. The switch is checked because the status is 1
  2. The switch remains checked when "Cancel" is clicked
  3. Upon clicking "Ok", the console logs 'true' and the switch remains checked

Update: When I add (ngModel)]="checkedBtn" in the HTML, all switches change instead of just one.

https://i.sstatic.net/oJDGs.png

Answer №1

To change the switch only when the user presses OK, follow these steps:

Here is how to do it in HTML:

<mat-slide-toggle  [(ngModel)]="checkedBtn" 
        (click)= "myfunction()"></mat-slide-toggle>

In TypeScript:

myfunction() {
    if (confirm('Are you sure?')) {

      console.log('true')

    } else {

      this.checkedBtn= !this.checkedBtn;
    }
  }

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

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

Exploring the HttpClient inheritance feature in Angular 6

I have customized the httpClient in an Angular project to include a special parameter in the options. This modification is working perfectly in my application. Here is the structure of my new service: export class CustomHttpClient extends HttpClient ...

Having trouble with the firebase.firestore.FieldValue.increment() function in Ionic?

I've encountered an issue while trying to utilize the Firebase increment function in my project. The framework I am using is Ionic 5.2.7. The following is my import statement for firebase: import { firebase } from '@firebase/app'; (I&apos ...

The new Angular 2 router in RC1 seems to have a glitch where the second level router-outlet only functions properly the

Check out this plunker example: http://embed.plnkr.co/B8feYX7e6oxvI2u4zmYW/ If you click on "Child 1", it works. However, clicking on "Child 2" does not work. Once you click "HOME", then clicking on "Child 2" works but "Child 1" does not. It seems the na ...

Navigating back to previous pages in an Angular(6) project connected to a Firebase Firestore database is a common requirement for

While there is an abundance of resources on how to paginate to the next page when using Angular with Cloud Firestore (Firebase), I have been unable to find a solution for pagination to a previous page. The closest I have come is returning to the first page ...

Mastering the Art of Typing a Function in TypeScript

I have a list of objects with an action field for each one, and I'm looking to simplify this field as follows: { id: '2', label: '', text: () => translate('MapAnnotation.Circle'), ic ...

Limit the TypeScript generic to a specific key that corresponds to a property of another generic

I currently have a setup with various interfaces and objects as outlined below: interface ServicesList { [key: string]: Service; } interface Service { uuid: string; characteristics: CharacteristictList; } interface CharacteristictList { [ ...

Using JQuery within Angular 4 is a valuable tool for enhancing the functionality

As a newcomer to Angular, I am experimenting with using jQuery alongside Angular 4. In my search for information, I stumbled upon this question on Stack Overflow. Inside the question, there was an example provided that can be found here. However, when att ...

The functionality of routerLink is not functioning as expected when used on button elements

My dashboard is designed to display information retrieved from Firebase. However, I am facing an issue with a button labeled as (more) that should redirect me to a specific page when clicked. Unfortunately, the button doesn't seem to be working as int ...

What advantages does asynchronous microservices communication offer when it comes to enhancing the user interface experience?

When working with my Angular UI, I make a call to an API gateway endpoint like this: this.http.post(`/order`).subscribe(order => addNewOrderToList(order)); Following best practices in microservices architecture, the /order handler should publish an ev ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

When the page is refreshed, Vercel's Next.JS success/error pattern is thrown due to the "window is not defined" error

Currently, I am working on enhancing a Next.js website that is hosted on Vercel. Upon deploying the page, I encountered the following error initially: GET] / 17:53:00:19 2022-09-12T14:53:00.262Z 938c1a2e-ce7c-4f31-8ad6-2177814cb023 ERROR Uncau ...

Using Angular 2+ to dynamically attach and detach from the mousemove event

I have experience binding to events using the HostListener decorator, as shown below: @HostListener('document:mousemove', ['$event']) onMousemove(event) { //Handling mouse movement. } However, I am looking for a way to dynam ...

The element is inferred to have an 'any' type due to the inability to use a 'string' type expression to index the 'Palette' type

Encountering an issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'. No index signature with a parameter of type 'string' was found on type &ap ...

Pass the condition as a variable to the class name in Angular

I need to apply a conditional class to a div. The issue I am facing is that I want the "myClassCondition" to be a string as shown below. When I use <div [class]="7 > 6 ? 'bg-red' : null"> MyText </div>, it works perfectly. However, ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Navigating between primary and named routes in Angular using RouterLink

After struggling for a while, I finally managed to get this code working: this.router.navigateByUrl('/live-chat(subnav:subnav)'); However, I am facing difficulty in replicating the same behavior using a [routerLink]='' directive. The m ...

Issues arising while fetching data with Angular httpClient

Hey there! I'm currently working with a basic controller that is returning some simple data. Here's the code snippet: [HttpGet("[action]")] public AppSettings GetStuff() { var stuff = new Stuff { Dummy = "Hi" }; return stuf ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Accessing route parameters in Angular directly from the templateFinding route parameters in

There are times when my routes have multiple parameters like: /checklists/:type/:view/:filter I want to generate links in the template in this manner: <a routerLink="['/checklists',':type',':view',':filter']"> ...