在Angular2中如何知道ANY表单输入字段何时失去焦点 [英] in Angular2 how to know when ANY form input field lost focus

查看:146
本文介绍了在Angular2中如何知道ANY表单输入字段何时失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2中,如何知道任何输入字段何时失去焦点..! 如果我在表单上使用可观察对象:

In Angular2 how to know when ANY input field has lost focus..! If I use observables on the form:

form.valueChange.subscribe...

无法工作,因为我真的很想知道字段丢失的时间是模糊的(焦点),所以我可以更新我的商店(如果我在失去焦点之前更新商店,那么我在文本输入上的光标会移到末尾,因为数据被交换,看起来很奇怪)

wont work since I really want to know when a field lost it's blur (focus) so I can update my store (if I update the store before losing focus, my cursor on a text input gets moved to the end, since the data gets swapped which is weird looking)

当然我也可以在每个输入上添加(change)="",但是我有很多'em ...

of course I can also add (change)="" on each input, but I have a lot of'em...

我在想某种事情:

this.form.valueChanges.debounceTime(1000).subscribe((changes:any) => {
  if (this.form.dirty){
    this.appStore.dispatch(this.resellerAction.updateResellerInfo(changes))
  }
});

但是问题是脏东西仍然很脏,所以它陷入了变化检测的永恒循环中……

but the problem is that the dirty remains dirty, so it stuck in an everlasting loop of change detections...

tx

塞恩

推荐答案

blur事件不会冒泡,因此我们需要直接侦听每个输入元素. Angular为这种情况提供了一个很好的解决方案.

The blur event doesn't bubble, therefore we need to listen on every input element directly. Angular provides a nice solution for this situation.

适用于模板内所有输入元素的指令.

A directive that applies to all input elements inside your template.

此伪指令使用主机侦听器侦听选择器所应用的所有元素上的blur事件,并转发冒泡的input-blur事件:

This directive uses a host-listener to listen for the blur events on all elements where the selector applies and forwards a bubbling input-blur event:

@Directive({
  selector: 'input,select',
  host: {'(blur)': 'onBlur($event)'}
})
class BlurForwarder {
  constructor(private elRef:ElementRef, private renderer:Renderer) {}

  onBlur($event) {
    this.renderer.invokeElementMethod(this.elRef.nativeElement, 
        'dispatchEvent', 
        [new CustomEvent('input-blur', { bubbles: true })]);
    // or just 
    // el.dispatchEvent(new CustomEvent('input-blur', { bubbles: true }));
    // if you don't care about webworker compatibility
  }
}

通过将BlurForwarder指令添加到directives: [...],它将应用于模板中与选择器匹配的所有元素.
主持人侦听器监听冒泡的input-blur事件并调用我们的事件处理程序:

By adding the BlurForwarder directive to directives: [...] it will be applied to all elements in its template that match the selector.
The host-listener listens for bubbling input-blur events and calls our event handler:

@Component({
  selector: 'my-component',
  directives: [BlurForwarder],
  host: {'(input-blur)':'onInputBlur($event)'},
  template: `
<form>
  <input type="text" [(ngModel)]="xxx">
  <input type="text" [(ngModel)]="yyy">
  <input type="text" [(ngModel)]="zzz">
</form>`
}) {
  onInputBlur(event) {
    doSomething();
  }
}

这篇关于在Angular2中如何知道ANY表单输入字段何时失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆