Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
tom Avatar asked Jan 19 '26 14:01

tom


2 Answers

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.

like image 157
ConnorsFan Avatar answered Jan 21 '26 05:01

ConnorsFan


there is no $event.target when you're emitting the component instance using output. You can however, emit the elementRef of your component using this.ee.next(this.elementRef)

Inject the elementRef in your constructor:

constructor(elementRef: ElementRef) { }

like image 36
Joshua Chan Avatar answered Jan 21 '26 05:01

Joshua Chan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!