Checkbox with checked property does not return me any value

Asked

Viewed 102 times

0

I have a code where the person must select a modality of the academy, for example, the martial arts plan, the person must select which fight she wants. So I made the following code:

<div class="btn-group-vertical btn-group-toggle col-4"
     data-toggle="buttons"
     id="modalidade"
>
   <div *ngFor="let modalidades of planoDados?.PlanoModalidades">
      <label class="btn btn-outline-success col teste">
          <input
              #checkbox
              type="checkbox"
              name="modalidades"
              (click)="addCheckbox(checkbox.value)"
              [value]="modalidades.PlanoModalidadeID"
              [checked]="modalidades.PlanoModalidadeObrigatoria === '1'"
              [disabled]="modalidades.PlanoModalidadeObrigatoria === '1'"
          />
         <span class="lead">
            {{ modalidades?.PlanoModalidadeDescricao }}
         </span>
      </label>
   </div>
</div>

The logic is, display a checkbox for each existing mode, the value will be the ID of the mode, but if one of the modality is mandatory, it is already checked and disabled, I created an array that will receive exactly the values of each checkbox.

I made that TS code:

private myCheckBox: any[] = [];

addCheckbox(i) {
    let index = this.checkBox.indexOf(i)
    if (index === -1) {
      this.checkBox.push(i)

    } else {
      this.checkBox.splice(index, 1)
    }
  }

But I don’t get the checkbox value that’s checked and disabled, any way to fix it? Or even a better way to pick up checkboxes marked than their value. How to get the "checked" property from a checkbox?

  • Just take the modalities that are already mandatory in planoDados.Planomodalities[] and join with those being marked in Html.

  • It is worth creating an array for all marked modalities and for the mandatory, put it in the array in ngOnInit?

  • Dude I would do that, pick the obligatory ones would put in an array along with the ones being marked.

  • The problem is this, how do I take the value of what is already marked by being mandatory?

1 answer

0

To catch the value and the checked of your input[type=checkbox] amend the following content of

 (click)="addCheckbox(checkbox.value)"

for:

(click)="addCheckbox($event.target)"

and change the method code addCheckbox to be able to read the value and checked:

addCheckbox(checkbox: HTMLInputElement) {
    /* ... */
    console.log(checkbox.value, checkbox.checked);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.