Event Binding
- 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>
-
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><textareaformControlName="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.
-
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);}} -
Open your browser’s Devtools console.
-
Fill in the title and description fields and click the ‘create task’ button.
-
When clicking the ‘create task’ button, you should see the form data displayed in the console.
You have learned how to listen for an event to trigger a function.