Reputation: 213
Tried click event for element reference in typescript but not working.How to write click event for element reference.If anyone know please help to find the solution.
app.component.ts:
@ViewChild('testElem') el:ElementRef;
@ViewChild('testElem2') el2:ElementRef;
this.el.on('click',()=>{
alert("test");
});
app.component.html:
<div #el>testElem</div>
<div #el2>testElem2</div>
Upvotes: 3
Views: 22079
Reputation: 194
It's possible (an alternative) to use the Renderer2 service for listening to events on elements.
@ViewChild('testElement') element : ElementRef;
Inject the Renderer2 service
constructor(renderer2: Renderer2) {}
Add the event listener
this.renderer2.listen(this.element, 'click', () => { ... });
Upvotes: 0
Reputation: 236
You probably solved it by now, but for those who wondering..
Your elementRef
reference is wrong, and you should call the event functions on the nativeElement
property of elementRef
.
This should work:
app.component.html:
<div #el>testElem</div>
app.component.ts:
@ViewChild('el') testElement: ElementRef;
ngAfterViewInit() {
this.testElement.nativeElement.onmouseenter = () => console.log('mouse enter')
this.testElement.nativeElement.onclick = () => console.log('clicked')
}
Upvotes: 1
Reputation: 2143
You can make something like this:
app.component.html
<div #el">testElem</div>
app.component.ts
import { AfterViewInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'
import { fromEvent, Subscription } from 'rxjs';
@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class AppComponent implements AfterViewInit {
@ViewChild('el', { static: false}) el: ElementRef;
clickedElement: Subscription = new Subscription();
ngAfterViewInit() {
this.clickedElement = fromEvent(this.el.nativeElement, 'click').subscribe(() => console.log('element clicked'));
}
ngOnDestroy() {
// add this for performance reason
this.clickedElement.unsubscribe();
}
}
We are using the AfterViewInit
Hook because the DOM already exists here.
I hope I have been able to help you.
Upvotes: 7
Reputation: 6529
With this, you don't need @ViewChild
to write a click event.
app.component.html
<div #el (click)="onClick()">testElem</div>
app.component.ts
// a method on the class
onClick() {
console.log('element clicked');
alert('test');
}
I strongly think you shouldn't be using the element reference for this, but if you truly must:
@ViewChild('testElem') el:ElementRef;
ngOnInit() {
this.el.nativeElement.on('click',()=>{
alert("test");
});
}
Upvotes: 2