Reputation: 21
I'm trying to uncheck a previous selected checkbox based on clicking one new mat checkbox
My HTML:
<form [formGroup]="deleteform" (submit)="submit()">
<ul>
<li *ngFor="let test of getvalue?.food">
<mat-checkbox [disableRipple]="true" [value]="test.id" [name]="'test.id'"
aria-label="Value">{{test?.category[currentval]}}
</mat-checkbox>
</li>
<mat-checkbox (change)="unCheckAll($event)">None of Above
</mat-checkbox>
</ul>
<button>
submit <br>
</button>
</form>
MY TS:
deleteform: FormGroup;
this.deleteform= this.fb.group({
info: [
'',
[Validators.required],
],
});
unCheckAll($event) {
this.deleteform.reset();
}
So far I tried this but it's not working, Any solution to uncheck previous selected checkbox based on clicking a new checkbox.
Upvotes: 0
Views: 1083
Reputation: 3137
If you use Reactive Forms it's very simple. First create your FormGroup
like this:
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
userCheck1: new FormControl({ value: true }),
userCheck2: new FormControl({ value: true }),
userCheck3: new FormControl({ value: true }),
});
}
reset() {
this.form.reset();
}
}
Here is the HTML part
<form [formGroup]="form">
<input type="checkbox" class="form-control" formControlName="userCheck1" />
<input type="checkbox" class="form-control" formControlName="userCheck2" />
<input type="checkbox" class="form-control" formControlName="userCheck3" />
</form>
<button (click)="reset()">Reset</button>
If you bind the input with the formControlName
attribute to your FormGroup
then it works as well.
Here is a Stackblitz.
If you wanna deselect any checkbox if you click another you can do it like this: HTML
<form [formGroup]="form">
<input type="checkbox" class="form-control" formControlName="info" (click)="disableOthers('info')" />
<input type="checkbox" class="form-control" formControlName="info2" (click)="disableOthers('info2')"/>
<input type="checkbox" class="form-control" formControlName="info3" (click)="disableOthers('info3')"/>
</form>
<button (click)="reset()">Reset</button>
<input type="checkbox" (click)="reset($event)" />
Code
disableOthers(controlName: string) {
Object.keys(this.form.controls).forEach((key) => {
if (key !== controlName) this.form.get(key).setValue(false);
});
}
If you click any checkbox the method will called with the key of the FormGroup
and uncheck all the other checkboxes.
Upvotes: 1