Angular's interactive checkboxes and dropdown menus provide a dynamic user experience

There is a global List array where data from an API is passed in the OnInit method.

List: any;
visibility:any;
Status:any;

ngOnInit(): void {
 let param = {...};
 this.Service.getUser(param).subscribe(result => {
      this.List = result['response'];
 });
}
now creating dynamic checkboxes and dropdowns
       <div class="example-box" *ngFor="let user of List;let i = index">
                      <input type="checkbox" [(ngModel)]="visibility[i]">
                      {{ user.Name }} 
                        <select name="status" [(ngModel)]="Status[i]">
                            <option value="1" selected>Active</option>
                            <option value="0">Inactive</option>
                        </select>
                      
       </div>

The issue arises when trying to update values simultaneously by looping through the main array. How can one fetch the dropdown and checkbox values at each index and save them as follows:

  {
        "Name": "John",
        "visibility": 0,
        "IsActive": 1
    },
    {
       "Name": "Peter",
        "visibility": 1,
        "IsActive": 1
    },
    ...


  

It's important to note that the cdk dragdrop feature is being used, requiring a loop through the entire list after sorting. Any suggestions would be greatly appreciated. Thank you!

Answer №1

To create a mapped array with the "enriched" items, simply use map.

this.List.map((item, index) => ({ 
  ...item, 
  visibility: visibility[index], 
  isActive: Status[index] 
}))

It's not entirely clear how your visibility and Status properties are defined, but it should work the same way in your template.

Please Note:

  • Be mindful of naming conventions. Typically, properties should start with lowercase keys.
  • You can streamline the process by initially mapping and then binding directly to your model using [(ngModel)], instead of defining separate arrays. Having separate arrays could lead to errors if they fall out of sync due to adjustments.

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 modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

Is there a way to reset the yAxes count of a chart.js chart in Angular when changing tabs?

I am currently using chart.js within an Angular framework to visually display data. Is there any method available to reset the y-axis data when changing tabs? Take a look at this Stackblitz demo for reference. Upon initial loading of the page, the data ...

Issues with displaying results from a local JSON file using Angular 4 services seem to be

I have developed a User.service.ts service where I have implemented the following code: getContactDetials(){ return this.http.get(this.config.apiUrl + 'assets/data/contact-details.json') .map(response => response.json()); ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

The placeholder string is being accepted as the input value for the number

My issue is with a form input of type number. When the form is submitted without entering any number, it treats the placeholder text "rating" as the value. How can I stop this from happening? I need to make sure that the input number field is marked as in ...

React - Incorrect use of hooks and class components

Understanding hooks as the opposite of a class component can be confusing. A simple line of code can trigger an error when trying to adapt it for use in a class component. Take, for example, this situation: .jsx files and functional components work seamles ...

Angular Dropdown Menu

When working with Angular, I encountered an issue with creating a drop down. Despite having a list of items, only the first item is displayed in the drop down menu. <div class="form-group"> <h4>Projects</h4> <div *ngFor="let ...

What is the best way to enhance the object type within a function parameter using TypeScript?

If I have a specified type like this: type Template = { a: string; b: string; c: string } I want to utilize it within a function, but with an additional parameter. How can I achieve this efficiently? When attempting to extend the type, TypeSc ...

Is it possible to continuously activate an Angular Input setter using a Subject?

Is there a way to activate an @Input setter without providing a value, by utilizing RxJS' Subject()? It seems that the setter only gets triggered once, most likely because no value has been changed. How can I ensure that the input is activated every ...

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

The combination of TypeScript decorators and Reflect metadata is a powerful tool for

Utilizing the property decorator Field, which adds its key to a fields Reflect metadata property: export function Field(): PropertyDecorator { return (target, key) => { const fields = Reflect.getMetadata('fields', target) || []; ...

What is the best way to use a single schema in MongoDB to create an object with an array?

Currently, I am working on creating a single Schema for Author with their respective quote. Here's what my model looks like at the moment: const mongoose = require("mongoose"); const AuthorSchema = new mongoose.Schema({ name: String, quote: ...

Utilizing Angular 4 Typescript to create cascading drop-downs within a table

As a newcomer to Angular, I am in the process of building my first application using Angular 4 and TypeScript. I would like to implement Cascading dropdowns within a table using Angular 4. Currently, I am facing an issue where changing the dropdown selec ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Steps for fixing the error message "Type 'Observable<string>' is not assignable to type 'Observable<{ userId: string; partyId: string; }>'"

Having some trouble with my Angular project. I have this code snippet in my getUser() method, but the compiler isn't happy about it and I can't seem to figure out what's wrong: public getUser(): Observable<{ userId: string; partyId: strin ...

Is there a way to execute the function of component2 that is embedded in the HTML display of component 1?

There are 2 components in my application - principal and menu. The menu component includes a JSON object and HTML code where clicking on an element should trigger a function in the principal component. Upon clicking this function, the selected object shoul ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...