我不能 运行 2 个我用 Angular 异步创建的复选框

I can't run 2 checkboxes that I created with Angular asynchronously

我有 2 个复选框,当我点击其中一个时,它应该是“true”,另一个是“false” 因此,如果选中一个,则必须取消选中另一个。我不应该同时检查两者。

      <div class="export-content">
        <input style="margin-right: 5px;" type="checkbox" value="1" [(ngModel)]="dataModal.analysis">
        <span>{{'EXPORTER.analysis' | translate}} </span>
      </div>
      <div class="export-content">
        <input style="margin-right: 5px;" type="checkbox" value="2" [(ngModel)]="dataModal.pressAnalysis">
        <span>{{'EXPORTER.pressAnalysis' | translate}} </span>
      </div>

   <button type="button" class="btn btn-sm btn-outline-primary" (click)="selectedDocumentsExpoertClick()">
      Print
  </button> 

这部分是我的 html 代码。

这部分是我的ts代码;

selectedDocumentsExpoertClick() {
    if (this.dataModal.analysis) {
       print details...
}
if (this.dataModal.pressAnalysis) {
  print details...
}

I have 2 checkboxes, and when I click on one of them it should be "true" and the other "false"

要获得准确的行为,您应该使用单选按钮而不是复选框。复选框用于select几个值所以当你点击一个框时其他人将继续使用以前的值。

1。添加导入以使用反应形式 app.module.ts

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
  imports: [
    FormsModule, <---
    ReactiveFormsModule, <---
    ....
  ])

2。初始化组件中的表单

    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。将表单添加到您的 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>