HTML5 event handling(onfocus and onfocusout) using angular 2

271,358

Solution 1

Try to use (focus) and (focusout) instead of onfocus and onfocusout

like this : -

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

also you can use like this :-

some people prefer the on- prefix alternative, known as the canonical form:

<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">

Know more about event binding see here.

you have to use HostListner for your use case

Angular will invoke the decorated method when the host element emits the specified event.@HostListener is a decorator for the callback/event handler method

See my Update working Plunker.

Working Example Working Stackblitz

Update

Some other events can be used in angular -

(focus)="myMethod()"
(blur)="myMethod()" 
(submit)="myMethod()"  
(scroll)="myMethod()"

Solution 2

If you want to catch the focus event dynamiclly on every input on your component :

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

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

  constructor(private el: ElementRef) {
  }

  ngAfterViewInit() {
       // document.getElementsByTagName('input') : to gell all Docuement imputs
       const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            });
            input.addEventListener('blur', () => {
                input.removeAttribute('placeholder');
            });
        });
    }
}

Checkout the full code here : https://stackblitz.com/edit/angular-93jdir

Solution 3

I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

Solution 4

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

Share:
271,358
vishnu
Author by

vishnu

Updated on August 21, 2020

Comments

  • vishnu
    vishnu almost 4 years

    I have a date field and I want to remove the place holder by default.

    I am using javascript onfocus and onfocusout events for removing placeholder.

    Can anyone help with using angular2 directive?

    <input name="date" type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="dateinput">
    

    I try to solving in this way, but i am getting problem with resetting the input field type.

    import { Directive, ElementRef, Input } from 'angular2/core';
    @Directive({
        selector: '.dateinput', 
        host: {
        '(focus)': 'setInputFocus()',
        '(focusout)': 'setInputFocusOut()',
      }})
    
      export class MyDirective {
          constructor(el: ElementRef) { this.el = el.nativeElement; console.log(this.el);}
    
          setInputFocus(): void {
            //console.log(this.elementRef.nativeElement.value);
          }
      }
    
  • Pardeep Jain
    Pardeep Jain about 8 years
    where you have used your directive named as dateinput ?
  • Pardeep Jain
    Pardeep Jain about 8 years
    @vishnu see my Updated plnuker
  • kbpontius
    kbpontius about 7 years
    Something to note, if you use the default HTML implementation, it may use the global scope when calling the designated function. For example: onfocusout="someMethod()" someMethod(), in this case, will be called in the global scope. That's another reason why using Angular in this case is valuable.
  • Pardeep Jain
    Pardeep Jain over 5 years
    @user5365075 I didn't see any such update, see here ng6 demo using focus stackblitz.com/edit/…
  • user5365075
    user5365075 over 5 years
    My mistake, focus will work on supported inputs and textareas, but if you have custom components that don't support it, you can use focusin instead :)
  • Saad Abbasi
    Saad Abbasi almost 4 years
    onfocusout="myFuntion()" does not work in angular 9 , (focusout)="myFunction()" Thanks @PardeepJain
  • Pardeep Jain
    Pardeep Jain almost 4 years
    @SaadAbbasi onfocusout should be working like on-focusout, for more reference please refer to a working example.