Blur not working - Angular 2

BeniaminoBaggins picture BeniaminoBaggins · Sep 1, 2016 · Viewed 16.7k times · Source

I'm trying to set a blue event in angular 2 like so:

<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() never gets executed. Why?

Answer

Stefan Svrkota picture Stefan Svrkota · Sep 1, 2016

Your blur event is not working because your div can't receive focus in the first place. If you add tabindex="1" (1 can be replaced with any number) or contentEditable (this will make div's content editable) to your div, it will be able to receive focus and then blur event will work. Plus, you can then use focus instead of click.