模糊不起作用 - Angular 2

Blur not working - Angular 2

我正在尝试在 angular 2 中设置一个蓝色事件,如下所示:

<div id="area-button" (blur)="unfocusAreaInput()" class="form-group" (click)="focusAreaInput()">

component.ts:

import { Component, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';
import { GoogleplaceDirective } from 'angular2-google-map-auto-complete/directives/googleplace.directive';

@Component({
    selector: 'my-area',
    directives: [GoogleplaceDirective],
    templateUrl: 'app/find-page/area-picker.component.html',
    styleUrls: ['app/find-page/area-picker.component.css']
})
export class AreaComponent {
    public address: Object;
    @ViewChild('areaInput') areaInput;
    areaSelected: boolean = false;
    @Output() onAreaSelected = new EventEmitter<boolean>();
    @Output() onAreaDeselected = new EventEmitter<boolean>();

    constructor(el: ElementRef) { }
    getAddress(place: Object) {
        this.address = place['formatted_address'];
        var location = place['geometry']['location'];
        var lat = location.lat();
        var lng = location.lng();
        console.log("Address Object", place);
    }

    focusAreaInput() {
        this.areaInput.nativeElement.focus();
        this.onAreaSelected.emit(true);
    }

        unfocusAreaInput() {
        this.onAreaSelected.emit(false);
    }
}

unfocusAreaInput() 永远不会执行。为什么?

您的 blur 活动无法正常运作,因为您的 div 一开始就无法获得焦点。如果您将 tabindex="1"(1 可以替换为任何数字)或 contentEditable(这将使 div 的内容可编辑)添加到您的 div,它将能够接收焦点,然后 blur 事件将起作用。另外,您可以使用 focus 而不是 click

使用tabindex属性。 设置

tabindex="0" 

将在获得焦点时给予最高优先级,因此您的 blur 事件将起作用

您也可以在 div 上尝试 (focusout)="unfocusAreaInput()"。当 div 中的任何可聚焦元素失去焦点(包括删除元素时)并且 div 中的其他一些元素没有同时聚焦时,它将触发。

如果您想知道 div 中哪个元素失去了焦点,您可以像这样传递:(focusout)="unfocusAreaInput($event.target)".

更多信息在这里: https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event