What is the best approach to dynamically iterate over checkboxes in Angular?

I have a hardcoded checkbox that looks like this:

https://i.sstatic.net/UVVCM.png

The code snippet is as follows:

<h5>Document List</h5>
<div class="form-check">
   <label class="form-check-label" for="check1">
   <input type="checkbox" class="form-check-input" id="check1" name="proformaInvoice" value="something" [(ngModel)]="processAnexOne.proformaInvoice" value="checked" >Proforma Invoice
   </label>
</div>

The JSON data being received can be viewed here:

https://i.sstatic.net/ckeWq.png

To fetch the JSON data from an API, I use this method:

ngOnInit() {
         this.http.get('http://localhost:8080/api/documents')
      .subscribe((data: any[]) => {
        this.documents = data;
        console.log(this.documents);
      })
  }

Is there a way to dynamically bind this JSON data to the checkbox?

Answer №1

If you want to loop through the documents array in Angular, you can make use of the *ngFor directive. Remember to include a new property called selected inside each document object and bind it to the checkbox value.

<div class="form-check" *ngFor="let document of documents">
   <label class="form-check-label" for="check1">
   <input type="checkbox" class="form-check-input" 
        id="check1" name="proformaInvoice"
        [value]= "document.docName"
        [(ngModel)]="document.selected"
        >Proforma Invoice
   </label>
</div>

Answer №2

To ensure the data is already available in your HTML, utilize ngIf to check for its presence before displaying the div.

Within the nested div, implement ngFor loop on your documents array.

<h5>Document List</h5>
<div class="form-check" *ngIf="dataIsPresent">
  <div *ngFor="let document of documents">
   <label class="form-check-label" for="check1">
   <input type="checkbox" class="form-check-input" name="document.docName" value="something"  value="document.docName" >{{document.docName}}
   </label>
  </div>
</div>

In your TypeScript file, initialize a boolean variable to track the arrival status of data.

dataIsPresent: Boolean = false;
ngOnInit() {
         this.http.get('http://localhost:8080/api/documents')
      .subscribe((data: any[]) => {
        this.documents = data;
        this.dataIsPresent = true;
        console.log(this.documents);
      })
  }

If you have any further questions, feel free to ask.

Answer №3

One way to efficiently iterate through documents and create checkboxes in Angular is by using the *ngFor directive.

<div *ngFor="let obj of documents">
    <div class="form-check">
       <label class="form-check-label" for="check1">
           <input type="checkbox" class="form-check-input" id="check1"
           name="proformaInvoice" value="something" 
           [(ngModel)]="obj.value" value="checked" >Proforma 
           Invoice
       </label>
    </div>
</div>

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

Utilizing razor syntax within JavaScript

I've encountered an issue with the code snippet below. I am trying to check if any content exists in my model and then use a ternary operator to show or hide based on its existence. $(document).ready(function() { (@Model.MyProperties.Any()) ? ...

Creating a like button using AJAX in Django

Is there a way to implement a like button in Django using ajax without the need for a page reload? I've tried setting up my HTML and Ajax function, but it's not working properly. <form method="POST" action="{% url 'video: ...

Click on the dropdown menu to reveal a form, and simply click outside of it to make

My dropdown menu with form elements hides when anything outside of it is clicked, but unexpectedly also closes when I click inside the element. This makes it difficult to complete a form. Below is the function causing this behavior: $(function(){ $(& ...

To concatenate an array into a single line, you can use the JSON.stringify() method

Could someone help me with using JSON.stringify to keep my data on the same line in an array? I am aiming for a format like this: "alice": { "college": "Stanford", "favorite_color": "purple", "favorite_numbers": [7, 15] }, "dave": { "college": "H ...

Angular4 Error: Unable to link to 'ngClass' as it is not recognized as a property of 'input'

Currently, I am facing an issue in my project where I am utilizing lazy loading. Specifically, within my registration module, I am attempting to utilize the [ngClass] directive to append an 'invalid' class when there are validation errors present ...

There is no output generated by Node.js express

I have encountered an issue where moving app.listen to the top results in a port in use error. I suspect this is because my websocket setup is using the same port, but I'm unsure how to resolve this. var server = require('websocket').server ...

Issues with the uib-datepicker-popup component in my Angular application are causing functionality to

Having trouble with the uib-datepicker-popup in my Angular application. It works fine in other controllers. <input ng-click="open($event, 'delivery_time_popup')" type="text" class="form-control" uib-datepicker-popup="dd-MMMM-yyyy" show-weeks= ...

Utilizing React/Redux to perform individual fetch calls for specific routes

I have a Redux store that needs to be connected to my App, but I only want to fetch data relevant to the component currently rendered by react-router. Currently, it is connected to a container element (App.js) which passes all props to the router's c ...

Issues with arguments not being identified - Discord.js version 14

After discovering that my arguments are no longer being recognized when executing a command, I encountered a strange issue. When args are not included, my console logs undefined, but if args are added, nothing is logged. This is snippet of my command hand ...

Transform unidentified individuals into authenticated users using Firebase Authentication for Google

Currently, I am integrating Firebase Auth with VueJS and facing the challenge of converting an anonymous authentication user to a registered user using Google. I have implemented the following code snippet from a reference: fromAnonymousToGoogle: funct ...

What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array: arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherTh ...

Adding a Row to an HTML Table Inside a Form through JavaScript

I'm currently attempting to insert a row into a table that resides within a form using JavaScript. The strange thing is, the code functions perfectly when it's placed outside of the form tags. However, as soon as I enclose the code within the for ...

Assistance with Collision Detection in HTML5 Canvas using JavaScript

Attempting to create a platformer game using HTML5 and the canvas feature. I managed to implement collision detection with rectangles, but encountered issues when adding multiple rectangles. I have a function that adds new objects to an array with attribut ...

The output display is not visible

I am currently working on a tutorial to showcase contact details on my webpage. However, I am facing an issue where the code is not displaying the first and last name as expected. Below is the code snippet for reference. Snippet from index.html <!DOCT ...

Steps to update the color of checkbox labels

I'm struggling with changing the colors of checkbox values based on their status - when checked, I want the text to display in green, and when unchecked, I want it to be red. Below is a sample input type, but I can't figure out how to style the t ...

How can I execute a synchronous MongoDB query in Node.js properly?

When utilizing the Node.JS driver for MongoDB, I am interested in executing a synchronous query. Here is an example of what I am aiming to achieve: function retrieveSomething() { var database = new mongo.Db("mydatabase", server, {}); database.ope ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Organize a JavaScript object into a hierarchical child-parent structure

Currently, I'm dealing with a challenging problem that is really testing my brain: I need to manipulate a JSON file containing a one-depth array of data objects. The structure looks something like this: [ {"id":1, "name":"Sport", "parent_id":0, "chil ...

Error: Unable to set reference. The initial argument includes an undefined value in the 'gender' property of 'Users.ji8A7TkSldfdvieDqGxko9eV3Jy1'

I followed along with a Firebase Web Tutorial on YouTube about adding data to Firebase Database for an account settings tutorial. However, when I tried to implement the code provided, it didn't work. Can anyone offer any assistance? // Code snippet fo ...

Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list. List<PhonesContacts> phoneContacts = snapshot.data; Lis ...