Search⌘ K

Implementing Functionality to Add a New Course

Explore how to create and configure Angular forms using FormBuilder, FormGroup, and Validators to add new courses. Learn to consume REST APIs with CourseService and Router, and handle form submission and validation to enable adding a course within the application.

To implement the functionality to add a course, we’ll head over to the dashboard components of our application and follow the steps below:

Step 1: Setting up the FormBuilder

We start by heading to our create-course directory. We currently have the design implemented, but we’re yet to configure FormBuilder, FormGroup, and Validators. To do that, we’ll head over to the create-course.component.ts file and implement the code below:

TypeScript 3.3.4
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-create-course',
templateUrl: './create-course.component.html',
styleUrls: ['./create-course.component.css'],
})
export class CreateCourseComponent implements OnInit {
createForm!: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.createForm = this.formBuilder.group({
name: ['', Validators.required],
isCompleted: ['', Validators.required],
link: ['', Validators.required],
platform: ['', Validators.required],
description: ['', Validators.required],
});
}
ngOnInit() {}
}

Below is a summary of the above code:

  1. We start by importing the FormBuilder, FormGroup, and Validators in line 2.
  2. Next, we create a createForm! variable in line 9. This variable holds the instance of the FormGroup. The exclamation mark at the end of the variable serves as an initializer to help prevent TypeScript errors.
  3. In line
...