Skip to content

Inject Service in form component

  • ✔️
    Use TaskService to create a task
    Use TaskService from TaskFormComponent to creat a new task

Inject the TaskService in the TaskFormComponent

🎓 Instructions

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

    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 implements OnInit {
    task = {
    title: '',
    description: ''
    };
    constructor(private taskService: TaskService) { }
    ngOnInit() {}
    createTask() {
    this.taskService.addTask(this.task);
    }
    }

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

Let’s test it out

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

You should see the new task in the list.

✔️ What you learned

You learned how to use the TaskService once gain, this time to trigger the addTask function to add a new task to the task list.