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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With