Inject the Service in the Form
Chapter Objective
Inject a service into a form component in Angular.
Inject TaskService into TaskForm component
Section titled “Inject TaskService into TaskForm component”The first step is to inject the service into your component.
-
Update the file
src/app/task-form.ts.task-form.ts import { Component, inject } from "@angular/core";import { TaskService } from "../task-service";@Component({selector: "app-task-form",templateUrl: "./task-form.html",styleUrls: ["./task-form.css"],})export class TaskForm {private taskService = inject(TaskService);form = new FormGroup({title: new FormControl(''),description: new FormControl('')});submit() {this.taskService.addTask(this.form.value);}}
The TaskFormComponent class now uses TaskService to add a new task to the list.
Let’s test it
Section titled “Let’s test it”- Go back to your browser
- Click on the
Add new tasklink - Enter a title and description in the form
- Click the
Submitbutton - Click on the
Task listlink
You should see the new task in the list.
What you've learned
You’ve learned to use TaskService once again! This time to trigger the addTask function to add a new task to the task list. Well done! 🤩