Home > front end >  How to to listen to an html element that is outside angular app?
How to to listen to an html element that is outside angular app?

Time:07-14

I have two HTML elements below,

<p #test>with reference</p>
<p id="with-id">need to access without template reference</p>

I know I can access the first P element with the template reference with renderer2 but I am not sure how I access the second P tag without template reference.

In our case,

Our modal is served outside our angular app. I need to add a click event to the close button of the modal which I directly don't have access to.

Below is my code,

this.unlistenCloseButton = this.renderer2.listen('outside-html-element', 'close', event => {
    console.log(`on close`);
});

Is there a way to add a reference to that close button and pass it to the angular's renderer2?

Here is a stackblitz code demonstrating with two P tag.

CodePudding user response:

On the popup close, am not sure if you use jquery or just javascript, but you need to call this below code (when the modal closes). Which will create a custom event.

const event = new Event('popupClosed');

// Dispatch the event.
document.dispatchEvent(event);

Then in the angular component listen for this document event using hostlistener.

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  @HostListener('popupClosed', ['$event.target'])
  onUnSelect(el) {
    console.log(el); // element that triggered event, in this case HTMLUnknownElement
    console.log('popupClosed');
  }
}

Code taken for the answer here

CodePudding user response:

Disclamer I don't know if this work, but Angular is not more than javascript. You can use document.getElementById and you can use fromEvent rxjs

  constructor(@Inject(DOCUMENT) private document:Document) {}

  ngAfterViewInit() {
    const el=this.document.getElementById('with-id')
    fromEvent(el,'click').subscribe(res=>{
      console.log(res)
    })
  }

NOTE: I choose use rxjs fromEvent operator, because allow get an observable, subscribe/unsubscribe, etc.etc. But you can also use addEventListener at javascript style

stackblitz

Update unsubscribe is important. So we can use some like

subscription:Subscription;
addEvent()
{
   if (this.subscription)
   {
      this.subscription.unsubscribe();
      this.subscription=null
   }
   const el=this.document.getElementById('with-id')
   this.subscription=fromEvent(el,'click')
             .pipe(take(1))
             .subscribe(res=>{
                console.log(res)
             })
}
  • Related