Reputation: 301
I am producing some divs using ngFor:
<div *ngFor='let img of images'>
I want to pass the div just produced to a function. At first, I tried to just pass a number to the function
<div *ngFor='let img of images' (being)="ToRunEachTime(img)">
where being is a directive like:
@Directive({
selector: '[being]'
})
export class beingDirective {
@Output() being: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
ngOnInit() {
this.being.emit('anything');
}
}
This code works well and I am able to pass img (which is a number) each time to the function ToRunEachTime. However, I wish to pass the whole div which is just created by *ngFor to this function. I tried:
<div *ngFor='let img of images' (being)="ToRunEachTime($event)">
but the function
ToRunEachTime(event: Event){
var currentdiv= <HTMLDivElement>event.target;
}
gives me undefined. Any Help is appreciated!
Upvotes: 0
Views: 589
Reputation: 41571
In your directive you are emitting a string
which does not contain the target
property
export class beingDirective {
@Output() being: EventEmitter<any> = new EventEmitter<any>();
constructor(private el:ElementRef,private renderer:Renderer2) {}
ngOnInit() {
this.being.emit(this.el.nativeElement);
}
}
If you are looking to emit any Browser event you should be adding a HostListener
as below and emit that event
@HostListener('mouseover', ['$event']) onClick(event) {
this.being.emit(event);
}
This will give you the target
element. Updated the demo.
Upvotes: 1