Search⌘ K
AI Features

Setting up the Activated Route to Update a Course

Explore how to use Angular's ActivatedRoute to fetch and prefill course data for editing. Understand routing setup, form configuration with FormBuilder, and consuming REST APIs to update courses.

Configuring the ActivatedRoute

The ActivatedRoute is an API that holds observable data about a route related to a component loaded in an outlet. To implement ActivatedRoute, we follow the steps below:

Step 1: Implement routing and navigation

We start by opening the course-list.component.html file, and then in the edit icon tag, we create a click event handler called editCourse(), which contains a parameter of the courseId. In the code widget below, we have the (click) event handler that contains the editCourse function in line 30.

HTML
<div class="container mt-3 px-2">
<div class="mb-3 d-flex justify-content-between align-items-center">
<div class="position-relative">
<button routerLink="/create-course" type="button" class="btn btn-outline-primary">Add New Course</button>
</div>
</div>
<div class="table-responsive">
<table class="table table-responsive table-borderless">
<thead>
<tr class="bg-light">
<th scope="col" width="20%">Title</th>
<th scope="col" width="10%">Status</th>
<th scope="col" width="20%">Course Link</th>
<th scope="col" width="20%">Platform</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{course.name}}</td>
<td [ngStyle]="{'color':course.isCompleted === false ? 'red' : 'green' }">
{{course.isCompleted}}
</td>
<td><a href={{course.link}} target="_blank"> {{course.link}} </a></td>
<td>{{course.platform}}</td>
<td><i class="fas fa-trash-alt" style="color: red; cursor: pointer;"></i>
</td>
<td>
<i (click)="editCourse(course._id)" class="fas fa-edit" style="color: blue; cursor: pointer"></i></td>
</tr>
</tbody>
</table>
</div>
</div>

Step 2: Router configuration

To configure the router, we need to head to our course-list.component.ts file and implement the code below:

TypeScript 3.3.4
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CourseService } from 'src/app/services/course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css'],
})
export class CourseListComponent implements OnInit {
courses: any;
constructor(private courseService: CourseService, private router: Router) {}
ngOnInit() {
this.fetchCourses();
}
fetchCourses() {
this.courseService.getCourses().subscribe(
(data) => {
this.courses = data;
console.log(this.courses);
},
(error) => {
console.log(error);
}
);
}
editCourse(id: any) {
this.router.navigate([`/edit-course/${id}`]);
}
}

Below is a summary of the code in the widget above:

  1. We import Router in line 2. We then inject it inside the constructor in line 12.
  2. In
...