Creating a checkbox list in Angular tied to ngModel and additional attributes sourced from a JSON array

I am currently developing an application using Angular. I have created a checkbox list where each checkbox has a specific ngModel value assigned to it.
To achieve this, I have defined a JSON object in my TypeScript component file which looks like this :

test = [
    {id: 'model1', site: '1', label: 'Clocher', view: 'file_clocher'},
    {id: 'model2', site: '1', label: 'Moulin', view: 'file_moulin'},
    {id: 'model3', site: '1', label: 'Poisson', view: 'file_poisson'},
    {id: 'model4', site: '2', label: 'Lacs', view: 'file_lac'},
    {id: 'model5', site: '2', label: 'Relais', view: 'file_relais'},
    {id: 'model6', site: '3', label: 'Citadelle', view: 'file_citadelle'},
]

In the HTML file, below is the code for the checkboxes:

<div *ngFor="let j of test">
<div *ngIf="j.site == '1'" class="form-check">
<input class="form-check-input" type="checkbox" [(ngModel)]="j.id" (change)="displayData($event)" name="{{j.view}}"/>
<label class="form-check-label">{{j.label}}</label>
</div>
</div>

The displayData($event) function is meant to retrieve the name parameter of the checked checkbox.
Therefore, in my TypeScript file, I have implemented...

displayData(event: any){
  console.log(event.target.name);
}

... and upon checking the first checkbox, the console should log e.g "file_clocher".

However, there are two issues I am facing:

  1. All the checkboxes appear to be pre-checked, which is unexpected
  2. When selecting the first checkbox, the console outputs "undefined" instead of the expected value such as "file_clocher" (manual testing without JSON data works fine)

If you have any suggestions on how to rectify these problems, I would greatly appreciate your assistance.

Thank you in advance for your support.

Answer №1

There are a couple of issues to address here: the ngmodel for input represents the value of the input field, which is typically boolean for checkboxes. Since j.id has been defined, it evaluates to a truthy value, causing all checkboxes to be checked by default. It may be beneficial to create another variable to track whether these inputs are checked.

You can set the name using [name]='j.view', or you can modify the function to simply pass in the view name like so:

(change)="displayData(j.view)"

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

Tips for adding a border to a table cell without disrupting the overall structure of the table

Looking for a way to dynamically apply borders to cells in my ng table without messing up the alignment. I've tried adjusting cell width, but what I really want is to keep the cells' sizes intact while adding an inner border. Here's the sim ...

Unable to generate a search query for the attribute because the query selector has not been specified

Currently facing an issue with a component in Angular 2 that comprises of other components. The components within the 'main' component can appear multiple times in the hierarchy. However, I encountered the following error: "Can't create a q ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

What is the process of accessing the changelog.md file within a component in Angular?

My challenge is to showcase the content from my changelog.md file, which is situated at the same level as the package.json file. I created a service for this purpose using the following code, function getData() { return http.get('../c ...

The symbol displayed on the computer screen representing the software known as Angular 2

Can a desktop icon be created for an Angularjs 2 application? I am looking to have an icon that, when clicked, opens the application's URL in the browser. ...

Exploring the contrast between string enums and string literal types in TypeScript

If I want to restrict the content of myKey in an object like { myKey: '' } to only include either foo, bar, or baz, there are two possible approaches. // Using a String Literal Type type MyKeyType = 'foo' | 'bar' | &ap ...

Steps for fully deactivating a mui/material Checkbox

Can someone help me with the issue I'm having regarding a Checkbox component from @mui/material? Here's the code snippet: <Checkbox color="primary" checked={isItemSelected} ...

TypeScript error TS2305: The auth.service module does not contain a named export for 'AuthService'

When I was working on the routing and navigation code provided at https://angular.io/docs/ts/latest/guide/router.html. Using -- node v6.9.4 and npm v4.1.1, VSCode 1.8.1 IDE, Ubuntu 16.04 I encountered the following error: app/auth-guard.service.ts( ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

How to toggle all checkboxes in Angular 2

Can anyone help me figure out how to select/unselect all checkboxes in my code? I've tried looking at other examples but haven't been successful. In the code below, I have managed to select/unselect individual units by clicking on them. When I c ...

Ngrx reducer is failing to trigger even when the state is accurately configured

I am working with a basic state structure: { items: Item[] selectedItems: string[] } In my application, I have a list of items with checkboxes. When I select an item, the list state is updated to include that item in the selected items array. However, ...

Guide on deploying an Angular application to function on the domain root, while storing it in a distinct folder within the webapps directory of Tomcat server

Recently, I purchased a VPS server and successfully installed Tomcat 10. My goal is to run my Angular app on the domain root at www.example.com, instead of having it as a subdirectory like www.example.com/myapp. Additionally, I prefer to deploy the Angul ...

Retrieving data synchronously from a Promise with Angular

I am looking to display the product history by retrieving the id of the product from the ActivatedRoute.params. In the ngOnInit method, I need to fetch all the historical records of the product and store them in a variable. Afterwards, I want to merge the ...

Utilizing props in styled-components: A beginner's guide

I am trying to pass a URL to a component so that I can use it as the background image of the component. Additionally, I need to check if the URL is empty. Component: <BannerImg/> CSS (styled): `const BannerImg = styled.img` background-image: url( ...

Having trouble launching React application on local machine due to missing node modules

I am completely new to React. I recently forked a project on Github and am attempting to run it on my own machine. However, I've noticed that the folder structure is missing the node modules. Does this mean I need to install create-react-app globally ...

Inquiry from a novice Angular user

Hello fellow members of the Angular community, I am embarking on an Angular project for my school and it's my first time delving into this framework. I could really use some guidance to get started smoothly. Initially, I set up a new project, instal ...

Customizing PrimeNG Dropdown: Concealing input and label elements with personalized styles

New to working with PrimeNG here. I'm looking for a way to get rid of the input and label elements in my project or simply hide them using CSS. I've heard that setting ViewEncapsulation to None is not the best solution. Currently, my component is ...

What methods can be used to avoid getting distracted by input?

Is there a way to prevent the input field in angular-material2 from gaining focus when clicking on a visibility button? To see an example of how it works, visit: material.angular.io Image before pressing the button: https://i.stack.imgur.com/5SmKv.png ...

Unable to view loggly-winston debug logs on the user interface

I am having an issue where I cannot see any logs when calling winston.debug. It seems like the log level allowed to be seen needs to be changed. For more information, refer to the winston documentation or the Loggly node.js documentation. To start, instal ...

There seems to be a glitch in my JavaScript for loop as it is not iterating for the correct amount that it should

It seems like my for loop is not always iterating 7 times as intended. Sometimes it runs with 5 iterations, other times with 4 or 3. This is the JavaScript code I am using: var start = new Date().getTime(); var end = new Date().getTime(); function timeT ...