LABS
COOKIES

Event Binding

Git diff Code changes
Chapter Objectives
  • Understand event binding

    Learn how to handle user interactions in Angular components.

  • Implement event handlers

    Create methods to respond to user events in your components.

  • Use event binding syntax

    Master the syntax for binding events in Angular templates.

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.

  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.

  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've learned

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