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
@forloop is used to iterate usersuser.idis tracked for better performance- 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
idis passed dynamically- URL becomes like:
-
/edit/2 - 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
- Reactive Form Controls are used
[formControl]binds input fields with TypeScript variables- 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
ActivatedRouteis used to read URL parametersidcomes as a string- API is called using this ID
- 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
setValue()fills input fields automaticallyageis converted to string because input expects string