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
- The switch is checked because the status is 1
- The switch remains checked when "Cancel" is clicked
- 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.