Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a 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>

My goal is to utilize template-driven forms to retrieve the values of all selected checkboxes in an array format, like this:

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

Just as a reminder:

While I have successfully used Reactive forms to create a FormGroup->FormArray that provides the following form value:

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

I am then able to filter out based on 'selected' property being true.

I am interested in exploring how to achieve something similar with template-driven forms.

Answer №1

You have the option to connect a template variable to the checkbox and then retrieve 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>

Next, in your component's class:

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

To access your array later on:

const selected = this.checkboxes
      .map(t => t.nativeElement)
      .map(checkbox => checkbox.checked

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After the Parent Component has successfully mounted, the Child Component will render

I am currently working with a third party library that has a unique prop allowing the user to pass in a string which is used to retrieve a DOM element and return its bottom value. <Sticky bottomBoundary="#some-id"> <MyChildComponentMightBeANa ...

The function call datatables rows().ids() does not return a defined value

I have implemented the ID attribute for rows in my datatable: 'createdRow': function (row, data, dataIndex) { $(row).attr('id', data.json.unid); } Now, I am trying to retrieve the IDs under a button click: action: function () { ...

Troubleshooting problems with Angular 6 update through the command "ng update"

https://i.stack.imgur.com/LuPSs.png I am currently in the process of upgrading from Angular version 5 to 6. When using the "ng update" command, I encountered a problem that is shown in the attached screenshot. Can someone guide me on how to resolve this ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Unforeseen behavior in Ajax success callback

My unordered list contains a href link. Initially, only the welcome page is visible on page load. Upon clicking the list for the first time after page load, the desired results are displayed in the corresponding div as expected. The issue arises when swi ...

JavaScript: Trouble with statement execution

My code is designed to classify a point as 1 if it's above the line y=x, and -1 if it's below the line y=x. I visually represent this line in a canvas by plotting y=x (although due to invertion on the y-axis, it appears like y=-x). For each point ...

Creating an Angular project that functions as a library and integrating it into a JavaScript project: a step-by-step guide

Is it feasible to create an Angular library and integrate it into a JavaScript project in a similar manner as depicted in the image below? The project structure shows trading-vue.min.js being used as an Angular library. Can this be done this way or is th ...

Can the ng-keypress listen for arrow key presses?

I'm looking to implement a functionality similar to the konami code "up, up, down, down, a, b, a, b, enter" -> triggering an action. Is it feasible to detect arrow key presses using ng-keypress in AngularJS? It doesn't seem to be working as e ...

Determine the data type of a parameter by referencing a prior parameter

Consider a scenario in my software where I have two distinct implementations of an Event Emitter. For instance: type HandlerA = (data: boolean) => void; type HandlerB = (data: number) => void; // HandlerB is somehow different from HandlerA type Eve ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

Best practices for assigning values to model field in EXT JS are as follows:

I'm facing an issue with a certain model structure: Ext.define('my.workspace.Area', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'string'}, {n ...

MUI Step Indicator Icon is not visible

I'm having trouble getting the MUI Stepper Component to display Icons within each step node. Despite following the sample code provided by MUI, my implementation only shows a blank screen instead of the desired look. The desired appearance includes i ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

Saving a PHP form with multiple entries automatically and storing it in a mysqli database using Ajax

My form includes multiple tabs, each containing various items such as textboxes, radio buttons, and drop-down boxes. I need to save the content either after 15 seconds of idle time or when the user clicks on the submit button. All tab content will be saved ...

The asynchronous functionality for reading and writing files from 'fs' is not functioning properly

I've been working on a script that reads and writes files, and so far the functions are functioning properly. However, I am facing challenges in making the read/write functions asynchronous. The main issue arises when trying to write a file and then i ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

What are the steps to styling a component with CSS Emotion?

I am facing an issue with using a theme with TypeScript in this component const buttonDisabled = css` color: ${({ theme }) => theme.color}; `; Is there a way to correctly type this component? Error: No overload matches this call. Overload 1 of 2, & ...

custom form control component combined with an issue

Trying to develop a custom MatFormFieldControl with ControlValueAccessor implementation. Starting off with a familiar scenario: password form. The objective is to design a form field that takes a single string input, but contains its own internal form fo ...