vendredi 30 octobre 2020

How to validate a checkbox group in Angular template-driven forms?

I have a form inside my app. I defined the form inside a page component and the form elements are all a separate component (input, checkbox, radio).

Now I want to validate all this components and this worked for the input fields, single checkbox and group radio buttons but I can't get the group checkbox working.

I have an array object, consisting of multiple objects (options), in these options you will find the value, label, and whether it is selected. The value of the selected option will be added to the value property.

When I do this in the same way as with the group radio buttons, the selected values are not correct, he immediately sets them to true and adds the values as true / false instead of the real value of the checkbox.

Below my code:

Object:

{
    id: "checkboxID",
    value: [],
    options = [
        {
            value: "checkboxvalue1",
            selected: false,
            label: "Checkbox1"
        },
        {
            value: "checkboxvalue2",
            selected: false,
            label: "Checkbox2"
        }
    ],
    disabled: false,
    readonly: false,
    required: false
}

Form component:

<form #myForm="ngForm">
    <checkbox></checkbox>
</form>

<pre></pre>

Group checkbox component

<div *ngFor="let option of options; let i = index">
    <input type="checkbox"
    #formItem="ngModel"
    class="checkbox-input"
    id="-"
    [name]="id"
    [(ngModel)]="value"
    [value]="option.value"
    [checked]="itemIsChecked(option, value)"
    [required]="required"
    [disabled]="disabled"
    [readOnly]="readonly"
    (change)="onChange(option.selected, formItem.value)"
  />

    <label class="label" for="-">
    
  </label>

    
</div>

Used ControlContainer, NgForm for controlling the forms. See Stackblitz for more

The checkbox option values are coming from the options array, and the model for the checkbox is the value property which is an array (possible to check multiple boxes).

The value of the group radio is updating well in the myForm.value, but the checkbox doesn't work well. Both options are checked on load, which is not correct and when I make an change the value appears as true / false instead of the real value.

When I remove the ="ngModel" and [(ngModel)]="value" inside the template, the checkbox works well (see stackblitz Group checkbox 1) but this time I can't do the validation.

How to solve this issue and make validation for the group checkbox inside a template-driven possible?

Stackblitz




Aucun commentaire:

Enregistrer un commentaire