Exploring Angular v12 Part 7 – Handling events

This post will go through a small example of how to use the click and keyup event handlers in Angular 12.

Template file

The following component has two native elements, a button and an input. The goal is to fire a function;

  • when the button
  • when text is typed in the input field

The value of the input is also controlled, and rendering in the ending p tag. For this to work the event must be binded with the relevant name, in the buttons case, this is (click), whereas the input’s is (keyup).

<section>
  <button (click)="handleClick()">click me</button>
  <input
    placeholder="enter some text"
    name="my input"
    (keyup)="handleKeyUp($event)"
    [value]="value"
  />
  <p>current value is {{ value }}</p>
</section>

Component file

In the body of the component file, I created two functions which are to fire when the events are triggered. An alert to show when the button is clicked, and a component level variable to set the value of the input, as text is being typed in it. In order to clear Typescript errors, the event.target must be casted as HTMLInputElement such that the value attribute is not undefined/null.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-events',
  templateUrl: './events.component.html',
  styleUrls: ['./events.component.scss'],
})
export class EventsComponent implements OnInit {
  value: string = '';

  constructor() {}

  ngOnInit(): void {}

  handleClick() {
    alert('button clicked');
  }

  
  // note: event.target must be casted to avoid TS errors
  handleKeyUp(event: KeyboardEvent) {
    this.value = (event.target as HTMLInputElement).value;
  }
}

Source code

Source code is available here

Leave a comment

Website Built with WordPress.com.

Up ↑