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