Skip to content

Event binding

Chapter Objectives

  • ✔️
    Event binding
    Learn how to bind an event to a function in Angular.

Event binding

Event binding allows you to listen for events and execute a function when the event is triggered. In the current situation, you will execute a function when clicking on the ‘Create task’ button.

On the HTML <button> tag, you can bind the click event to a function using the (click) syntax. You assign it the function you want to execute when clicking the button.

<button type="submit" class="btn btn-primary" (click)="submit()">Submit</button>

In the TaskFormComponent class, you need to create the linked function. Without it, Angular will not compile.

🎓 Instructions

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

    task-form.component.html
    <form>
    <label for="title" class="form-label">Title:</label>
    <input
    type="text"
    id="title"
    name="title"
    class="form-control"
    [(ngModel)]="task.title"
    />
    <label for="description" class="form-label">Description:</label>
    <textarea
    id="description"
    name="description"
    class="form-control"
    [(ngModel)]="task.description"
    ></textarea>
    <button type="submit" class="btn btn-primary" (click)="submit()">
    Submit
    </button>
    </form>

submit Function

You will create a submit function to handle form submission. For this step, you will only log the form value to the console.

🎓 Instructions

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

    task-form.component.ts
    import { Component } from "@angular/core";
    @Component({
    selector: "app-task-form",
    templateUrl: "./task-form.component.html",
    styleUrls: ["./task-form.component.css"],
    })
    export class TaskFormComponent {
    task: TaskForm = {
    title: "",
    description: "",
    };
    submit(): void {
    alert("Task created", this.task);
    }
    }
  2. Open your browser’s Devtools console.

  3. Fill in the title and description fields and click the ‘create task’ button.

  4. When clicking the ‘create task’ button, you should see the form data displayed in the console.

✔️ What you have learned

You have learned how to listen for an event to trigger a function.