Angular Add EventListener to Component Only Worked Once

372 Views Asked by At

I have an Angular application where multiple components (Let's say A, B, C) use a common smaller component (Let's say M). M is basically a bootstrap modal and I tried to add event listener to it. The event listener I tried to bind is a Bootstrap event show.bs.modal, so I cannot use the usual event binding way Angular provides. I did this by

ngOnInit(): void{
  let myModal = document.getElementByid("MyModal")
  myModal?.addEventListener("show.bs.modal", ()=>{
    console.log("I'm open")
  })
}

I'm successful on the first binding, and I can fire the event if I open M in A. However, if I switch to B or C, or switch back from B or C to A, that event listener seems gone. I cannot fire the event if I open M in B or C, or A after I came back from B or C.

I searched the questions for the cause but was not so successful. I saw a lot of people saying that you should bind event listeners in ngAfterViewInit instead, but I tried that too and it didn't give me a different result. The code is basically the same:

ngAfterViewInit(): void{
  let myModal = document.getElementByid("MyModal")
  myModal?.addEventListener("show.bs.modal", ()=>{
    console.log("I'm open")
  })
}

So what happened to those event listeners? And if I want the event listener to be with M whenever and wherever I open the modal, how should I do it? Thank you!

0

There are 0 best solutions below