Skip to content

Inject the service into the form component

Chapter Objectives

  • ✔️
    Use TaskService to create a task
    Create a new task with the TaskFormComponent using the TaskService.

Inject TaskService into TaskFormComponent

The first step is to inject the service into your component.

🎓 Instructions

  1. Modify the file src/app/task-form.component.ts.

    task-form.component.ts
    import { Component } from "@angular/core";
    import { TaskService } from "../task.service";
    @Component({
    selector: "app-task-form",
    templateUrl: "./task-form.component.html",
    styleUrls: ["./task-form.component.css"],
    })
    export class TaskFormComponent {
    task = {
    title: "",
    description: "",
    };
    constructor(private taskService: TaskService) {}
    submit() {
    this.taskService.addTask(this.task);
    }
    }

The TaskFormComponent class now uses TaskService to add a new task to the list.

Let’s test it

  1. Go back to your browser
  2. Click on the Add new task link
  3. Enter a title and description in the form
  4. Click the Create task button
  5. Click on the Task list link

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! 🤩