Search code examples
angularangular-directivedom-eventsangular-event-emitter

How to access the target of an $event bound to a DOM element using a custom directive?


I've created a directive

import {
  Directive, AfterContentInit, Output, EventEmitter
} from '@angular/core';

@Directive({ selector: '[attached]' })
export class AttachDirective implements AfterContentInit {

  @Output("attached")
  private ee: EventEmitter<AttachDirective> = new EventEmitter();

  ngAfterContentInit() { setTimeout(() => this.ee.next(this)); }

}

to define a custom event that should fire when a DOM element to which it is bound gets "attached" to the view. So for example <input (attached)="do something" ... does something as soon as the <input> shows up on the page.

The event fires well, my problem is however that when I'd like to access its target like <input (attached)="$event.target.something = 'anything'" I get an error such as

Cannot set property 'something' of undefined

How to upgrade my directive so I can access the target of the event?


Solution

  • To access the element as $event.target, define a target property that returns the HTML element to which the directive is applied:

    @Output("attached") private ev: EventEmitter<AttachDirective> = new EventEmitter();
    
    constructor(private elementRef: ElementRef) { }
    
    public get target(): HTMLElement {
      return this.elementRef.nativeElement as HTMLElement;
    }
    
    ngAfterContentInit() {
      this.ev.next(this);
    }
    
    <input type="text" (attached)="$event.target.disabled = true" >
    

    See this stackblitz for a demo.