How to create a Template driven formArray in Angular?

370 Views Asked by At

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

There are 1 best solutions below

0
On

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