Implement a system in Angular Service that automatically generates user IDs for an array of user inputs

How can I automatically increment the user ID for each new user input and use that value for deletion or updating of specific entries?

If a user adds their details as shown in the output picture link below, I want to display the output in a similar format. However, I am struggling to assign automatic user IDs to each input.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  userArray: any[] = [];
  userId: number[] = [];
  constructor() { }
  public getUsers(): any[] {
    return this.userArray;
  }
 
  public save(obj: any): void {
    this.userArray.push(obj);
  }

Below is the code for the UserService component:

export class StoreFormComponent implements OnInit {

  constructor(private builder: FormBuilder, private service: UserService) { }

  ngOnInit(): void {
  }
  userForm: FormGroup = this.builder.group({
    id: [''], // Problem: I want to store incremented IDs here for CRUD operations
    name: ['Lucifer'],
    gender: ['male'],
    phone: ['1231231'],
    email: ['example@email.com'],
    address: this.builder.group({
      state: ['LA'],
      city: ['CA'],
      pin: ['123123']
    })
  });
  
  saveForm() {
    this.service.save(this.userForm.value);
    console.log(this.userForm.value);
  }
  clear() {
    this.service.save({});
  }
}

Below is the HTML code for displaying the output:

<div>
    <h3>User List</h3>
   
    <table *ngIf="items" class="table table-striped">
        <thead>
            <tr>
                <th>User ID</th><th>Name</th><th>Gender</th><th>Phone</th><th>Email</th><th>State</th><th>City</th><th>Pin</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of items">
                <td>{{user.id}}</td> // Problem: I want to assign auto-incremented IDs to user inputs 
                <td>{{user.name}}</td>
                <td>{{user.gender}}</td>
                <td>{{user.phone}}</td>
                <td>{{user.email}}</td>
                <td>{{user.address.state}}</td>
                <td>{{user.address.city}}</td>
                <td>{{user.address.pin}}</td>
            </tr>
        </tbody>
    </table>
</div>

Images for reference:

Store Component Picture: Link

Output Picture: Link

Answer №1

If you're looking for a solution, consider incorporating something similar to this method. However, keep in mind that in actual practice, the ID should be generated from the server side, such as from the database itself.

  public addNewUser(user : any):void {
    const lastUser = this.usersArray[this.usersArray.length - 1];
    if(lastUser !== undefined){
       user.id = lastUser.id+1;
    }
    else{
       user.id = 0;
    }
    this.usersArray.push(user);
  }

It's also recommended to define an interface or type for the object instead of using any all the time, as it helps in maintaining the code better.

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

"Ways to retrieve an array of dates within a specified range of date and time

I am working with date fields in my project { tripScheduleStartDate: '2018-12-05T18:30:00.000Z', tripScheduleEndDate: '2018-12-07T18:30:00.000Z', } Is there a way to generate a datetime array from the start date to the end date, lik ...

The getJSON function callback is not functioning as expected

I'm new to working with JSON objects and sending them to the browser. I'm having trouble with the callback function not executing properly. I don't see anything in the console. $('#id').change(function(){ $.getJSON('ajax. ...

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Enhance your React Native experience with IntelliSense recommending react-native/types over react-native

I am trying to bring in <View from react-native, but instead, I am getting react-native/types https://i.sstatic.net/FeRKT.png How can I resolve this issue? This is a new project starting from scratch and I followed the documentation by adding TypeScri ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Nextjs build: The specified property is not found in the type 'PrismaClient'

I have a NextJS app (TypeScript) using Prisma on Netlify. Recently, I introduced a new model named Trade in the Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url ...

The modal is functioning properly on Firefox and Internet Explorer, but it is experiencing issues

Having an issue with my modal not functioning properly in Chrome. When I click on it, only the background fades and both the before and after content load in the Chrome Dev tools simultaneously with no visible content in between. Here is a link to the Cod ...

Compare the values of properties in an array with those in a separate array to filter in Angular/TypeScript

There are two arrays at my disposal. //1st array tasks.push({ ID: 1, Address: "---", Latitude: 312313, Longitude: 21312 }); tasks.push({ ID: 3, Address: "---", Latitude: 312313, Longitude: 21312 }); //2nd array agentTasks.push({ID:2,AgentID: 2,TaskID:1}); ...

transmit JSON data with an AJAX request and receive a response

I'm looking to make a JSON request to an API and receive a response. I tested it using Postman and successfully received the following response: JSON request to API: { "apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp" } The response I receiv ...

Is my implementation of async await the most efficient method to handle asynchronous operations in my code?

Struggling to implement and grasp async await functions in my login example, I'm uncertain if my code is the most optimal, elegant, and clean. I especially have doubts regarding error handling, and how to best utilize const and functional programming ...

Design a unique login portal separate from all other website pages

I'm a beginner with Angular and I'm currently working on creating a login page. My issue is that I want the login page to be the only component displayed initially, and once the response is 200, I want to redirect to another component. Here&apos ...

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

Include buttons in the HTML template once JSON data has been received

I am working on a feature to dynamically add buttons to the DOM using JSON data fetched from an API when users visit the site. Although I have successfully implemented the function to retrieve the data, I am facing challenges in adding these buttons dynami ...

Is the on-error event not functioning properly in the <img> tag?

I am currently utilizing VueJS to develop the front-end of a project and encountered an issue with the image tag when loading images. Template <div class="items" transition="fade" v-for="item in list"> <img :src="item.logoPath" @error="replac ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

Menu with hover functionality in JQuery that functions as a standard menu even when JavaScript is disabled in the browser

Is it possible to modify this code so that the hover point links' images do not appear if the browser has JavaScript disabled? And can the links function like a regular hover point even when JavaScript is disabled? <script type="text/javascript" s ...

Downloading Files in Angular Using HttpClient - Extracting File Names from the Server Response

I am currently working on retrieving a File from an API URL. My goal is to display this uploaded file in an input field along with its name. To achieve this, I have implemented the following service function: getDocument(): Observable<Blob> { c ...

When the application initializes, the Child Component is activated

There's a scenario where I need to trigger a component named 'cancellation' when the user clicks a button in another component called 'names'. To achieve this, I set a flag called loadCancellation to true when the Search button is ...