Search code examples
angulartypescripttypescript-types

What is the correct type for $event when using (blur) in Angular


<input type="text" (blur)="onBlur($event)" />
export class AngularComponent {
  public onBlur(event: any) {
    const value = event.target.value;
    // Do other things...
  }
}

In the above code, what is the correct typescript type for event? I would like to avoid using any here.


Solution

  • You can use Event for the blur, which will not have a value property in the type, for that we can cast the target to HTMLInputElement.

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <input type="text" (blur)="onBlur($event)" />
      `,
    })
    export class App {
      public onBlur(event: Event) {
        const value = (<HTMLInputElement>event.target).value;
        alert(value);
        // Do other things...
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo