Ari Roth
Ari Roth

Reputation: 5534

Angular2: Directive loads, but does nothing

EDIT: I found the problem. You know what it turned out to be? A chrome caching issue. Chrome cached something, and until I turned off caching while the debugger was open and explicitly refreshed my page, I was getting nowhere. Once I refreshed, I started getting events caught.

Original Post: I have a custom Angular directive that's supposed to act on a control on any of three events: onload, onblur, or onfocus. It's applied to an input control, which may or may not be disabled. I know that onblur and onfocus are useless on a disabled control, but I suppose there'd be no harm in listening for events that never appear. On the other hand, an enabled control will fire off those events, so I need to be listening. This directive is designed to be fairly generic, so it needs to handle both a disabled and an enabled input control.

The problem is, it does nothing. At the very least, it doesn't appear to do anything. The directive is instantiated -- I've verified that the constructor fires off, and I've verified that elementRef points to an input control -- but that's about it. None of the listeners work.

Usage:

<input myDirective disabled id="someId" name="someName" [ngModel]="myValue" />

Directive:

import { Directive, HostListener, ElementRef, Input } from "@angular/core";

@Directive({ selector: "[myDirective]" })
export class MyDirective {
    constructor(private elementRef: ElementRef) {
    }

    @HostListener("focus", ["$event.target.value"])
    onFocus(value: string) {
        console.log("MyDirective: Focus caught.");
    }

    @HostListener("blur", ["$event.target.value"])
    onBlur(value: number) {
        console.log("MyDirective: Blur caught.");
    }

    @HostListener("load", ["$event.target.value"])
    onLoad() {
        console.log("MyDirective: Load caught.");
    }
}

When I run everything, it loads fine. No issues with missing modules, missing components, etc. No errors in the console. As I mentioned earlier, even breaking into the code using the debugger verifies that the directive was instantiated. But I get no console output, either. I would at least expect it for the onload event. Do disabled input controls not fire those or something?

Upvotes: 0

Views: 260

Answers (1)

Aravind
Aravind

Reputation: 41571

onLoad will not work because it is a window event and not a form event

Following are the list of events that can be handled for Form Elements

onblur  
onchange
oncontextmenu   
onfocus 
oninput 
oninvalid   
onreset 
onsearch
onselect
onsubmit

You have refer to it from this documentation Update based on comment

As you expected a MDN link to support the above answer here it is

enter image description here

Resource events refers to the resources in the internet such as a web url.

Upvotes: 1

Related Questions