Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write click event for viewchild element reference in angular 8

Tags:

angular

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>
like image 626
Nila Vaani Avatar asked Jan 26 '26 04:01

Nila Vaani


1 Answers

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.

like image 72
Ricky Avatar answered Jan 29 '26 13:01

Ricky



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!