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

Encountering TypeScript errors when trying to reference Angular2 within a Gulp setup

The issue at hand is: [11:16:06] TypeScript: 103 semantic errors [11:16:06] TypeScript: emit succeeded (with errors) I am currently using node v5.7.0 and npm 3.6.0 gulp -v: [11:26:58] Requiring external module babel-register [11:26:58] CLI version 3.9 ...

Passing objects to Angular 4 routes while maintaining Query Params unchanged

I'm currently working with Angular 4 and I need to pass an object to the router without updating query parameters. user.component.ts this.router.navigate(["/profile",{ action: 'edit', user: {id: 1, name: 'test', email: &apo ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Transform a string into a class in Typescript/Angular

In my application, I've created a reusable modal popup component that takes a string as input and dynamically loads other components based on that input. This approach allows me to use the same modal popup component for multiple modals in the app inst ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Incorporating a filtering search bar in Ionic React to efficiently sort pre-existing lists based on their titles

Struggling to implement a search bar in my Ionic application has been quite challenging. I've searched for examples and tutorials, but most of them are based on Angular with Ionic. The React example in the Ionic docs didn't provide much help eith ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Issue with Angular 6 Animation not showing up

Looking to incorporate an animation spinner into my Angular app Found this spinner example: https://codepen.io/z-/pen/OPzNLz spinner.component.html import { Component, OnInit } from '@angular/core'; @Component({ selecto ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Working with Ngxs and WebSocket: How to intercept the connection and include a custom HTTP header

Currently, I am utilizing ngxs's NgxsWebsocketPluginModule to establish a websocket connection within my Angular application. In order to authenticate the connecting client, my server mandates an authentication token to be included in the HTTP headers ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Developing a hybrid application with .Net Core and Angular 2 is an achievable task

Currently, I am working on developing an application that involves utilizing .net core and angular2 technologies. Is it possible to integrate an angular component within Razor view Pages seamlessly? ...

Building Background Service Workers with React Scripts and webpack Configuration

I am currently developing a chrome extension using ReactJS and TS along with a service worker. Due to the new manifest V3 requirements, I am required to specify my service worker in a specific way: "background": { "service_worker": &q ...

There was an issue converting the value {null} to the data type 'System.Int32', resulting in a 400 error

Attempting to make a POST request with some missing data is causing errors in my angular form. Here is the payload I am using: DeviceDetail{ deviceId:'332', sideId: null, deviceName:'test' } Unfortunately, I encountered a 400 bad re ...

Find the combined key names in an object where the values can be accessed by index

I am currently working on creating a function called indexByProp, which will only allow the selection of props to index by if they are strings, numbers, or symbols. This particular issue is related to https://github.com/microsoft/TypeScript/issues/33521. ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

The error message "Property 'data1' is not a valid property on the object type {}"

const Page: NextPage = ({data1}:{data1:any}) => { const [open, setOpen] = React.useState(false); const [data, setData] = React.useState(data1); const handleAddClick = () => { setOpen(true); }; ..... } export async function getServerS ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

"Stay tuned for the latest updates on subscribing to Angular

In my Angular 7 code, I am trying to assign the result of a subscription to a specific variable, but it seems like the code is not working as expected. Here is an example of how my code looks: async getItemsbyId(id) { console.log('2') await ...