简体   繁体   English

为什么复选框以角度显示真假

[英]why checkbox showing true and false in angular

I have created checkbox in angular but when I selected all the checkbox it shows me true and false.我已经以角度创建了复选框,但是当我选中所有复选框时,它会显示 true 和 false。 But I am trying to get checkbox value not true and false in reactive form.但我试图以反应形式获取复选框值不正确和错误。

<input type="checkbox" formControlName="services" id="checkbox4" value="transcription">
<label for="checkbox4"><span>Transcription</span></label>
<input type="checkbox" formControlName="services" id="checkbox3" value="translation">
<label for="checkbox3"><span>translation</span></label>

I am getting true in return not the value of checkbox.我得到的回报不是复选框的价值。

How i can get the value?我如何获得价值?

I have tried to recreate your checkbox sample and it works perfectly fine.我已经尝试重新创建您的复选框示例并且它工作得很好。

  1. Wrap the input into form.将输入包装成表格。
  2. Create formgroup for the both inputs.为两个输入创建表单组。

In your component.ts file在你的 component.ts 文件中

form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      services: new FormControl()
    });
  }

  getValues(event: Event) {
    console.log(event.target.value, event.target.checked);
    this.selectedCheckbox[event.target.value] = event.target.checked;
  }

In your component.html在你的 component.html

<form (change)="getValues($event)" [formGroup]="form" (ngSubmit)="onSubmit()">
  <input
    type="checkbox"
    formControlName="services"
    id="checkbox4"
    value="transcription"
  />
  <label for="checkbox4"><span>Transcription</span></label>
  <input
    type="checkbox"
    formControlName="services"
    id="checkbox3"
    value="translation"
  />
  <label for="checkbox3"><span>translation</span></label>
  <p>Selected value: {{ selectedCheckbox | json }}</p>
</form>

Complete sample: https://stackblitz.com/edit/angular-hekmvm?file=src/app/app.component.html完整示例: https ://stackblitz.com/edit/angular-hekmvm?file=src/app/app.component.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM