如何在Angular 4中编写全局事件监听器?

4

我希望将以下jQuery代码转换成Angular 4。

jQuery代码在应用程序中的所有文本框上都可以正常工作,但希望在Angular中为所有input-text控件执行相同的操作。

困难在于

  • 在Angular 4中编写通用事件监听器。
  • 在Angular 4中操纵或遍历父级或同级元素。

提前感谢您。

$(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");
            }
        });

使用您的全局选择器创建一个指令,这样每个指令将应用于具有.mask-text的元素。然后,您可以操纵该元素及其子元素。 - Yordan Nikolov
1个回答

2

看起来你是Angular 4的新手。

创建一个名为InputFocus.directive.ts的文件。

将下面的代码粘贴到其中。

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', '');  
    } 
  }
}

您需要在应用程序根文件中导入此内容。通常将是 app.ts

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

确保路径正确。

现在找到 @NgModule 并在您的模块中添加 HighlightDirective。请参见下面的代码。不要复制全部内容,只需在 declarations 中添加 HighlightDirective

例如:

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

这应该可以工作。

查看演示示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接