I have 2 checkboxes, and when I click on one of them it should be "true" and the other "false" so if one is checked, the other must be unchecked. I shouldn't be able to check both at the same time.
<div >
<input style="margin-right: 5px;" type="checkbox" value="1" [(ngModel)]="dataModal.analysis">
<span>{{'EXPORTER.analysis' | translate}} </span>
</div>
<div >
<input style="margin-right: 5px;" type="checkbox" value="2" [(ngModel)]="dataModal.pressAnalysis">
<span>{{'EXPORTER.pressAnalysis' | translate}} </span>
</div>
<button type="button" (click)="selectedDocumentsExpoertClick()">
Print
</button>
this part is my html code.
and this part is my ts code;
selectedDocumentsExpoertClick() {
if (this.dataModal.analysis) {
print details...
}
if (this.dataModal.pressAnalysis) {
print details...
}
CodePudding user response:
I have 2 checkboxes, and when I click on one of them it should be "true" and the other "false"
To get the exact behavior you should use radio button instead of checkbox. Check box is used to select several values so when you click on a box the others will continue with the previous values.
1. Add imports to use reactive form to app.module.ts
...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule, <---
ReactiveFormsModule, <---
....
])
2. initialize the form in the component
import { FormControl, FormGroup } from '@angular/forms';
......
export class YourComponent implements OnInit {
public form: FormGroup = new FormGroup({
typeAnalysi:new FormControl('option1') //Option selected by default
});
....
onAnalysiSelected(typeAnalysi:string){
console.log(typeAnalysi)
}
onSubmit(formValue:any){
console.log(formValue)
}
}
3. Add form to your HTML your.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<div>
<label for="typeAnalysi">Type Analysis</label>
<div>
<label for="option1">
Option 1
<input (ngModelChange)="onAnalysiSelected(form.controls['typeAnalysi'].value)" id="option1" type="radio" name="typeAnalysi" formControlName="typeAnalysi" value="option1">
</label>
<label for="option2">
Option 2
<input (ngModelChange)="onAnalysiSelected(form.controls['typeAnalysi'].value)" id="option2" type="radio" name="typeAnalysi" formControlName="typeAnalysi" value="option2" />
</label>
</div>
</div>
</form>