Populate Form Data Using API - Edit User with Dynamic Routing

These notes explain how user data is shown in input fields when clicking the Edit button, using routing, API call, and reactive forms.


User List UI with Edit Button

This code displays the user list and provides Delete and Edit buttons for each user.


<h1>User List</h1>

<ul>
@for(user of usersData(); track user.id){
<div class="user-ul">
<ul>
<li>Name : {{user.name}}</li>
<li>Age : {{user.age}}</li>
<li>Email : {{user.email}}</li>
<li>Id : {{user.id}}</li>
</ul>

<div>
<button (click)="deleteUser(user.id)">Delete</button>
<button (click)="editUser(user.id)">Edit</button>
</div>
</div>
}
</ul>

Explanation

  1. @for loop is used to iterate users
  2. user.id is tracked for better performance
  3. Edit button sends user ID to the editUser() function


Navigate to Edit Page with User ID

When Edit button is clicked, user is redirected to edit page with ID in URL.

editUser(id: number | undefined) {
this.router.navigate([`edit/${id}`]);
}

Explanation

  1. id is passed dynamically
  2. URL becomes like:
  3. /edit/2
  4. This ID will be used to fetch user data


Edit User Form UI

This is the Edit User form where data will be pre-filled.

<h1>Edit User</h1>

<div>
<input type="text" placeholder="enter name" name="name" [formControl]="name">
<br><br>

<input type="text" placeholder="enter email" name="email" [formControl]="email">
<br><br>

<input type="text" placeholder="enter age" name="age" [formControl]="age">
<br><br>

<button (click)="editUser()">Update User</button>
</div>

Explanation

  1. Reactive Form Controls are used
  2. [formControl] binds input fields with TypeScript variables
  3. Same form is reused for updating user


Get User ID from URL

In ngOnInit(), user ID is extracted from the route.

ngOnInit() {
let id = this.activeRouter.snapshot.paramMap.get('id');
console.log(id);

if (id) {
this.userService.getUser(id).subscribe((data) => {
console.log(data);

this.name.setValue(data.name);
this.age.setValue(data.age.toString());
this.email.setValue(data.email);
});
}
}

Explanation

  1. ActivatedRoute is used to read URL parameters
  2. id comes as a string
  3. API is called using this ID
  4. Data is received and set into form controls


How Form Gets Pre-Filled

When API returns user data:

this.name.setValue(data.name);
this.age.setValue(data.age.toString());
this.email.setValue(data.email);

Explanation

  1. setValue() fills input fields automatically
  2. age is converted to string because input expects string