Angular Labs
COOKIES

Event Binding

Git diff Branch
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

An event is an action or occurrence, like a user clicking a button, typing in a field, or a page loading, that your application can respond to. The action of reacting to an event is called event listening.

Event binding

Event binding enables you to respond to user actions or occurrences by executing a function when an event is triggered. In the current situation, you will listen to the event triggered by clicking the ‘Create task’ button and execute a function.

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>
  1. Update the file src/app/task-form/task-form.html.

    task-form.html
    <form [formGroup]="form" class="flex flex-col gap-2 m-auto">
    <fieldset class="fieldset w-full">
    <legend class="fieldset-legend">Name</legend>
    <input formControlName="name" type="text" class="input w-full" placeholder="Type here" />
    </fieldset>
    <fieldset class="fieldset">
    <legend class="fieldset-legend">Description</legend>
    <textarea
    formControlName="description"
    class="textarea w-full h-24"
    placeholder="Description"
    ></textarea>
    </fieldset>
    <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. Update the file src/app/task-form/task-form.ts.

    task-form.ts
    @Component({
    selector: "app-task-form",
    // ...
    })
    export class TaskFormComponent {
    form = new FormGroup({
    title: new FormControl(''),
    description: new FormControl('')
    });
    submit() {
    console.log("Task created", this.form.value);
    }
    }
  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.