Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 使用角度模糊处理onblur事件_Angular_Typescript - Fatal编程技术网

Angular 使用角度模糊处理onblur事件

Angular 使用角度模糊处理onblur事件,angular,typescript,Angular,Typescript,使用jQuery,我可以简单地编写如下内容 $(document).on("blur", ".class_name", function(){} 为了触发class\u name元素模糊事件上的某些功能。我如何使用angular获得相同的结果 像这样的解决方案 <input (blur)='on_blur_function()'.... > 不幸的是,我的情况不能接受。谢谢。您可以轻松做到: 导入ElementRef并将其注入构造函数

使用jQuery,我可以简单地编写如下内容

$(document).on("blur", ".class_name", function(){}
为了触发
class\u name
元素模糊事件上的某些功能。我如何使用angular获得相同的结果

像这样的解决方案

<input (blur)='on_blur_function()'.... >


不幸的是,我的情况不能接受。谢谢。

您可以轻松做到:

导入ElementRef并将其注入构造函数

constructor(private elem: ElementRef){}
使用querySelectorAll api搜索元素

ngAfterViewInit(){
    let elements = this.elem.nativeElement.querySelectorAll('.class_name');
    elements.forEach(element => {
     // you can iterate through each element and call your function
     this.on_blur_function(); // call your function
 });
}

您可以创建指令并将类用作其选择器:

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

@Directive({
  selector: ".foo"
})
export class BlurredDirective {
  @HostListener("blur")
  blurred() {
    console.log("blurred");
  }

  constructor() {}
}

在模板中:

<input class="foo" >

如果您不想使用指令,您可以使用
ViewChildren
结合模板引用变量的独立方法:

导入{
AfterViewInit,
组成部分,
ElementRef,
OnDestroy,
QueryList,
查看儿童
}从“@角度/核心”;
从“rxjs”导入{fromEvent,Subject};
从“rxjs/operators”导入{takeUntil};
@组成部分({
选择器:“我的应用程序”,
模板:`
`,
样式URL:[“/app.component.css”]
})
导出类AppComponent实现AfterViewInit、OnDestroy{
@ViewChildren(“inputRef”)元素:QueryList;
ngUnsubscribe$=新主题();
ngAfterViewInit(){
this.elements.forEach(element=>{
fromEvent(element.nativeElement,“模糊”)
.pipe(takeUntil(此.ngUnsubscribe$))
.subscribe((事件:FocusEvent)=>this.customBlurEvent(事件));
});
}
恩贡德斯特罗(){
this.ngUnsubscribe$.next();
}
customBlurEvent(事件:FocusEvent){
console.log({event});
}
}
通过将
#inputRef
添加到输入中,您可以在
ngAfterViewInit
中初始化视图后查询它
rxjs
有一个名为
fromEvent
的可观察创建者,它接受一个源和一个事件类型,在本例中是输入和模糊事件。然后,您可以使用事件分派您的方法,在组件被销毁时从事件源取消订阅(因此我调用了
takeUntil
,以避免内存泄漏)