...

/

Setting up the Activated Route to Update a Course

Setting up the Activated Route to Update a Course

Learn to configure the ActivatedRoute in Angular.

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.

Press + to interact
<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:

Press + to interact
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
...