LABS
COOKIES

Inject the Service in the Form

Git diff Code changes
Chapter Objectives
  • Inject a service in the form

    Learn how to inject a service into a form component in Angular.

Inject TaskService into TaskFormComponent

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

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