UPDATE: Edit User in Angular

In this tutorial, you will update the User details.

Fetching User Data on Page Load


ngOnInit() {
  const id = Number(this.route.snapshot.paramMap.get('id'));

  this.userService.getUser(id).subscribe((user: any) => {
    this.form.patchValue(user);
  });
}

When the component loads, the User ID is retrieved from the route URL using paramMap.

getUser(id) is called to fetch the existing user details from the server.

patchValue() fills the form with the fetched data so the user can edit it.

This ensures the form displays the current information of the selected user.

Submitting the Updated Data


submit() {
  const id = Number(this.route.snapshot.paramMap.get('id'));

  this.userService.updateUser(id, this.form.value).subscribe(() => {
    this.router.navigate(['/']);
  });
}

When the user submits the form, the same user ID is read from the URL.

updateUser(id, this.form.value) sends the updated form data to the backend for saving.

After a successful update, the user is redirected back to the homepage (/).

Complete code into the file


ngOnInit() {
  const id = Number(this.route.snapshot.paramMap.get('id'));

  this.userService.getUser(id).subscribe((user: any) => {
    this.form.patchValue(user);
  });
}

submit() {
  const id = Number(this.route.snapshot.paramMap.get('id'));

  this.userService.updateUser(id, this.form.value).subscribe(() => {
    this.router.navigate(['/']);
  });
}

Reuse Same HTML (Add + Edit)

So there is no need to create another file to edit the user form fields.