ionBlur事件:检测正在获得焦点的元素

时间:2019-02-02 01:45:40

标签: angular ionic-framework

我想从一个自定义指令中确定发生模糊事件时接收焦点的元素是什么:

@Directive({
  selector: '[my-directive]',
  host: {
    //...
    '(ionBlur)': 'onBlur($event)'
  }
})
export class MyCustomDirective implements OnInit {
    //...
    onBlur($event) {
        console.log(event) // This logs a CustomEvent that contains information only about the element that losing the focus
        console.log(event.relatedTarget) // This logs undefined
    }
    //...
}

我将此指令与ion-input元素一起使用:

<ion-input my-directive></ion-input>

测试时,event方法的onBlur参数包含属性targetcurrentTarget,它们都是失去焦点的元素,但是 event.relatedTarget未定义:

enter image description here

是否也有可能获得焦点的元素?

2 个答案:

答案 0 :(得分:0)

首先,您将需要Hostlistener来监视模糊事件。 而当你发现模糊事件与HostListener:

  @HostListener('ionBlur', ['$event'])
  onBlur($event: FocusEvent) {
    console.log(event)
  }

您可以看到relatedTarget可用

enter image description here 但是

    console.log(event.relatedTaget)

将给出编译器错误。

由于它是JSON结构,因此我建议这样做:

console.log(event['relatedTarget'])

那么您将得到这个:

enter image description here

Demo

答案 1 :(得分:0)

我正在使用Ionic 4,对我来说最有效的方法是

onFocusLostEvent() {
    let input = event['target'] as HTMLElement;
    console.log(input.id); // the id of the ion-input object for its identification
}