0

I have a fix number of checkbox which I am binding using for loop.

<ul>
    <li *ngFor="let chk of checkboxes">
        <input type="checkbox" [id]="chk.id" [value]="chk.value"/>
        <label [for]="chk.id">{{chk.name}}</label>
    </li>
</ul>

what I am looking for is using template driven form to get a value all of selected checkboxes, something like following

{
    selected:[
        checkboxValue1,
        checkboxValue2,
        checkboxValue3,
    ]
}

NOTE:

I am able to use Reactive form to generate a FormGroup->FormArray which generates the following form value

{
    checkboxes:[
        {
            id: checkboxId1,
            value: checkboxValue1,
            selected: true,
        },
        {
            id: checkboxId2,
            value: checkboxValue2,
            selected: false,
        },
        {
            id: checkboxId3,
            value: checkboxValue3,
            selected: true,
        }
    ]
}

Which I am then filtering out with selected==true.

I was wondering how to do something similar with template driven form.

1
  • Not sure if this helps, but you can bind your chk.value property like this. Commented Dec 17, 2022 at 17:51

1 Answer 1

0

You can attach a template variable to the checkbox and then query it using @ViewChildren

<ul>
    <li *ngFor="let chk of checkboxes">
        <input #checkbox type="checkbox" [id]="chk.id" [value]="chk.value"/>
        <label [for]="chk.id">{{chk.name}}</label>
    </li>
</ul>

Then in your component class:

export class MyComponent {
  @ViewChildren('checkbox')
  checkboxes!: QueryList<ElementRef>
}

And to access your array:

const selected = this.checkboxes
      .map(t => t.nativeElement)
      .map(checkbox => checkbox.checked
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.