AmitV
AmitV

Reputation: 260

How can I write a global event listener in Angular 4?

I want to write below code that is in jQuery into Angular 4.

jQuery code is working fine for all text box in app but want to make same thing in angular which run for all input-text control.

Difficulties are

Thanks in advance.

$(document).on('focus ', ".mask-text input[type='text'], .mask-text input[type='password']", function (e) {
            $(this).parents(".mask-text").addClass("focused");
        });
        $(document).on('blur ', ".mask-text input[type='text'], .mask-text input[type='password'] ", function (e) {
            if ($(this).val() == undefined) {
                $(this).parents(".mask-text").removeClass("focused");
            }
        });

Upvotes: 4

Views: 3396

Answers (1)

Arjun Nayak
Arjun Nayak

Reputation: 1260

Looks like you are new to Angular 4.

Create a file called InputFocus.directive.ts

paste the below code in it.

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
 selector: '.mask-text input[type="text"]'
 })
export class HighlightDirective {

   constructor(private el: ElementRef) { 
   }

  @HostListener('focus') onFocus() {
    var cName = this.el.nativeElement.parentElement.className;
    if(cName.indexOf('focused') === -1){
      this.el.nativeElement.parentElement.className += " focused"; 
    }
  }

  @HostListener('blur') onBlur() {
    var data = this.el.nativeElement.value;
    if(!data){
      this.el.nativeElement.parentElement.className = this.el.nativeElement.parentElement.className.replace('focused', '');  
    } 
  }
}

You must import this in your app root file. Generally will be app.ts

import {HighlightDirective} from './InputFocus.directive'

See to it that the path is right.

Now find @NgModule and add HighlightDirective in your Module. See below code. Do not copy everything, just add the HighlightDirective in declarations.

eg

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App,
  HighlightDirective
  ],
  bootstrap: [ App ]
})

This should work.

See the Demo Example

Upvotes: 2

Related Questions