Skip to content

Event binding

  • βœ”οΈ
    Event binding
    Learn how to bind an event to a function in Angular

Event binding

Event binding allows to listen to events and execute a function when the event is triggered. In the current situation, you want to execute a function when the β€˜create task’ button is clicked.

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 the button is clicked.

<button type="submit" class="btn btn-primary" (click)="createTask()">Create task</button>

This function will be created in the component class.

πŸŽ“ Instructions

  1. Replace the content of the src/app/task-form/task-form.component.html file.

    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)="createTask()">Create task</button>
    </form>

createTask function

You will create a createTask function to handle the form submission. For this step, let’s just log the form value to the console.

πŸŽ“ Instructions

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

    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 implements OnInit {
    task: TaskForm = {
    title: '',
    description: ''
    };
    ngOnInit() {}
    createTask(): void {
    console.log('Task created', this.task);
    }
    }
  1. Open the devtools console in your browser.
  2. By clicking on the β€˜create task’ button, you should see the form data logged to the console.

🌱 Challenge

Fill the title and description fields and click on the β€˜create task’ button. Verify that the form value logged to the console is updated.

βœ”οΈ What you learned

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