onFocusEvent in Angular

Rana Hasnain Khan May 27, 2022
onFocusEvent in Angular

In this article, we will tackle the Angular focus() and explain with example how it works.

Use onFocusEvent() in Angular

We will see what the focus event in Angular 10 is and how we can use it. When an element gets its focus, the focus event is triggered.

# Angular

<input (focus)='functionName()'/>

The NgModule used by the focus event is CommonModule.

Let’s have a step-by-step example using the focus event.

  1. Create an angular app that we can use.
  2. In app.component.ts, create a function that triggers on focus event.
  3. In app.component.html, make an input element and set the focus event.
  4. Serve the angular app using ng serve to see the output.

Code - app.component.ts:

# Angular

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

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    onFocusEvent(): void {
        console.log('Focus Activated for this method');
    }
}

Code - app.component.html:

# Angular
<form>
    <input type="text" placeholder="Text" (focus) = 'onFocusEvent()'>
</form>

Output:

onfocus view in angular

Output in the console is displayed whenever we focus on the input field.

onfocus console log in angular

Let’s have another example where the message "Focus Activated for this method" displays in the console when clicking the button.

Code - app.component.ts:

# Angular

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

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    onFocusEvent(): void {
        console.log('Focus Activated for this method');
    }
}

Code - app.component.html:

# Angular

<br>
<form>
    <button (focus) = 'onFocusEvent()'>Click Me!</button>
</form>

Output:

onfocus event on buttons in angular

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Angular Event