【问题标题】:How can I write a global event listener in Angular 4?如何在 Angular 4 中编写全局事件监听器?
【发布时间】:2018-02-13 17:06:28
【问题描述】:

我想将下面的 jQuery 代码写入 Angular 4。

jQuery 代码适用于应用程序中的所有文本框,但希望在 Angular 中制作同样适用于所有输入文本控件的内容。

困难是

  • 在 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");
            }
        });

【问题讨论】:

  • 用你的全局选择器创建一个Directives,这样每个指令都将应用于带有.mask-text的元素,用于Exp。然后你可以操作元素及其子元素。

标签: jquery angular addeventlistener dom-manipulation


【解决方案1】:

看起来你是 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。请参见下面的代码。不要复制所有内容,只需在 声明 中添加 HighlightDirective

例如

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

这应该可行。

Demo Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2023-02-22
    • 2021-10-17
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多