简体   繁体   中英

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. 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

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

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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