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.
- Create an angular app that we can use.
- In
app.component.ts
, create a function that triggers on focus event. - In app.component.html, make an input element and set the focus event.
- 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:
Output in the console is displayed whenever we focus on the input field.
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:
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