0

So I went ahead and implemented a custom directive:

@Directive({ selector: 'input[applostfocus]' })
export class LostFocus {
    @Output()
    applostfocus = new EventEmitter<any>();

    @HostListener('focusout', ['$event.target' ])
    focusout(input) {
        this.applostfocus.emit(input);
    }
}

It listens to the onfocusout DOM Event, and emits an event.

If it is included in the module, it can be used like this:

<input type="number" (applostfocus)="numberLostfocus($event)"></input>

public numberLostfocus($event) {
    console.log("applostfocus");
}

However my question is: can It really be, that a @Directive like this does not exist in Angular 7?

I've searched the web and there were only solutions for AngularJS. Also I've been looking at the official docs. The reason why I'm asking, is because this feels slightly overengineered and unnatural to do with such an advanced framework.

For instance, you wouldn't have to make a custom directive to listen on a click event:

<button type="button" (click)="somemethod()"></button>

I wrote this question to make sure I'm doing it right, and that I'm not reinventing the wheel. I'd expect answers like:

  • Yes, You're doing It right, there is no such thing as because: ...
  • No, You were missing ...

Edit:

It's actually documented here.

Community
  • 1
  • 1
LuckyLikey
  • 3,504
  • 1
  • 31
  • 54

1 Answers1

3

You can use (blur)="numberLostfocus($event)" for the same purpose. It's built-in.

Vitalii Chmovzh
  • 2,825
  • 4
  • 14
  • 28
  • Yep that's It.. please kill me ^^ I wonder how I didn't find this. But its [here](https://angular.io/guide/user-input#on-blur) – LuckyLikey Jun 05 '19 at 06:56
  • They're not quite the same, e.g. [*"`focusout` bubbles whole `blur` does not"*](https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event). – jonrsharpe Jun 05 '19 at 06:56
  • @jonrsharpe so you're saying, that I could do `
    ` and it would still trigger it?
    – LuckyLikey Jun 05 '19 at 06:59
  • @LuckyLikey no, that's not what I'm saying (it's also not true, as your directive is specific to `input` elements); I'm saying that `blur` and `focusout` are not quite the same event. You can bind to `focusout` using, inevitably, `(focusout)="..."`. – jonrsharpe Jun 05 '19 at 10:26
  • @jonrsharpe yes, but what's meant by _bubbles whole_? Is it similar to `WPF`s `RoutingStrategy.Bubble`? [link](https://learn.microsoft.com/en-us/dotnet/api/system.windows.routingstrategy?view=netframework-4.8) – LuckyLikey Jun 05 '19 at 11:55
  • @LuckyLikey see https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture. *"Whole"* was a typo, sorry; the linked article says *while*. – jonrsharpe Jun 05 '19 at 13:17
  • @jonrsharpe so this basically means that the focusout event first runs through the capture phase then the bubble phase, while blur skips it. – LuckyLikey Jun 05 '19 at 19:33