An easy way to select multiple checkboxes from an array using Angular 6

When editing data, I have a form that includes checkboxes. I need to ensure that the previously selected checkboxes are checked in the edit profile form based on the array retrieved from the database.

Code snippet from app.component.html:

<form [formGroup]="editCategoryForm" > 
    <div class="form-group">
        <mat-form-field>
            <input matInput placeholder="Name"  formControlName="name" >
        </mat-form-field>
    </div>
    <div formArrayName="categoryArray" >  
        <fieldset *ngFor="let address of editCategoryForm.controls.categoryArray['controls']; let i = index" >
            <div [formGroupName]="i" >
                <div class="form-group">
                    <mat-form-field>
                        <input matInput placeholder="Label" formControlName ="label"  required>
                    </mat-form-field>
                    <br/>
                    <div class="check-box" *ngFor="let data of measurementData">
                        <input type="checkbox" (change)="onChange(i,data._id,data.name, $event.target.checked)"  > {{data.name}}
                    </div> 
                    <div class="col-sm-1">
                        <button mat-mini-fab color="warn" *ngIf="editCategoryForm.controls.categoryArray['controls'].length > 1" title="Remove Fields" (click)="removeLair(i)">x</button>     
                    </div>

                </div>
            </div>
        </fieldset> 
        <br/>
        <div class="form-group">
            <button mat-raised-button color="accent" (click)="addNew()">Add Measurement</button>
        </div>
        <div class="form-group">
            <button style="float: right;margin: 29px;"  mat-raised-button color="primary" (click)="submitdata()">Submit</button>          
        </div>  
    </div>
</form>

The following code captures an array of measurements from the database:

this.category = {
    "_id":"5c4b0d6918f72032c0569004",
    "name":"categorytest",
    "measurements": [{
        "measurements": [
            {"name":"Chest","id":"5c4ac1c4da2dfe251aeee037"},
            {"name":"Stomach","id":"5c4ac1d6da2dfe251aeee038"},
            {"name":"Hip","id":"5c4ac1dbda2dfe251aeee039"},
            {"name":"Length","id":"5c4ac201da2dfe251aeee03c"}
        ],
        "label":"testfff"
    },
    {
        "measurements":[{"name":"Chest","id":"5c4ac1c4da2dfe251aeee037"}],
        "label":"httt"
    }]
}

Code snippet from app.component.ts File:

this.https.post<any>('api/category/details', data).subscribe(response => {
    this.category = response.category;
    this.editCategoryForm.controls['name'].setValue(this.category.name);
    console.log(this.category);
    console.log(this.category.measurements.length);

    for (let i = 0; i < this.category.measurements.length; i++) {
        if (i !== 0) {
            const control = <FormArray>this.editCategoryForm.controls['categoryArray'];
            control.push(this.getData());
        }
        this.categoryArray.at(i).get('label').setValue(this.category.measurements[i].label);
    }
});

Feel free to check out this StackBlitz demo.

Answer №1

  validateInput(i,data){
    let inputValid = false;
    //console.log(this.category.measurements[i].measurements);
    //console.log('data = ', data);
    for (let index = 0; index < this.category.measurements[i].measurements.length; index++){
      let tempData = this.category.measurements[i].measurements[index];
      //console.log('inside =',tempData);
     if (tempData.name == data.name && tempData.id == data._id){
       inputValid = true;    } 
    }
    return inputValid;
  }

Insert the code above into your typescript file, then utilize it in your HTML file like this:

<input type="checkbox" (change)="onInputChange(i,data._id,data.name, $event.target.checked)"  [checked]="validateInput(i,data)"> {{data.name}}

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

How can one retrieve every element within nested associative arrays?

Situation : Upon receiving a JSON array from a jQuery <-> PHP Ajax request, the unparsed JSON array structure appears as follows: {"Focus":{"id":2,"brand":"Ford","name":"Focus"}} Upon using JSON.parse(json);, the structure transforms to: Foc ...

Getting the header component in home.vue within Vue.js: A step-by-step guide

Is there a way to hide a button in the header by using JavaScript to access the component inside Home.vue? I've attempted to retrieve the element ID of the button within Home.vue, but it remains unattainable. ...

Using an image as the background for a three.js scene may cause it to appear distorted

I am struggling with setting an image as a background for my scene without it becoming blurry. I have attempted to use the following code: textureLoader.load("images/background/space.png", function(t) { scene.background = t; }); The problem arises when ...

Comprehending Angular 5's Importing External Classes

I have developed a class structure for managing Schedules. I then brought in this class to my primary program. My issue arises from the fact that this class utilizes the HttpClient, which I was instructed to set up within the constructor. As a result, when ...

Continuously animate a series of CSS properties

Here's the code snippet I'm working with: @keyframes ball1 { 0% { transform: translateX(0px); opacity: 0%; } 50% { opacity: 100%; } 100% { transform: translateX(120px); opacity: 0%; } } @keyframes ball2 { 0 ...

Combining Angular with Google Maps

Currently, I am utilizing angular-googlemaps(agm) and it has been functioning well for me so far. However, I have a requirement to search for an address using latitude and longitude. After some research, I discovered a partial solution here. The only issu ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Align multiple elements in a responsive fixed container

I have been attempting to center multiple elements, including images and buttons, within a fixed div at the top of the screen. Despite trying various tricks I found online, none seem to be effective. My goal is to ensure that the alignment works seamlessly ...

Cut costs by saving checkbox states in local storage

I have a JavaScript function that creates a checkbox and listens for a change event: function test() { var a = document.getElementById('test'); var b = document.createElement('input'); b.type = 'checkbox'; b.a ...

Steps to Remove the Displayed Image upon Click

I have a collection of images such as {A:[img1,img2], B:[img1]}. My goal is to remove the array values that correspond to previewed images upon clicking the delete button. Each image is equipped with its own delete button for this purpose. This snippet ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

Selenium webdriver is having trouble selecting a value from an ajax dropdown

I am currently facing an issue where I am attempting to choose specific values from two Ajax drop down fields. The first drop down list opens up, but it is not selecting any options, which in turn prevents the second drop down list from populating. This er ...

The 'clientX' property is not recognized on the 'Event' type in Angular2 Directive

When attempting to retrieve the X position of my mouse in an Angular2 Directive using the following code: @HostListener('mousemove', ['$event']) onMousemove(event: Event): void { console.log(event.clientX) } I encountered an error ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Displaying a collection of nested objects in AngularRendering a group

Is there a way to render an object of objects in Angular without converting it into an array or similar structure? I have a large object of objects and I want to avoid multiple iterations through object-to-array conversions just to loop through the array i ...

What steps do I need to take to link my Angular production build to my Express API within a Docker environment?

Currently, I am working with an express API that is sending an empty JSON object to localhost:3001/. I have successfully deployed the API on Docker and it is running smoothly. Now, I am trying to access it from my Angular application but I am encounterin ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

Retrieve properties from an object that correspond to the class definition in Typescript

Hey there, I have an object structured like this: let o = {"foo":"blah", "blah": "foo", "foo2":"blah2"} In addition, my class is defined as follows: class Foo { constructor(public foo: string, blah: string) {} } I am curious if there is a way to insta ...