Search code examples
clickangular9mat-dialog

Open MatDialog via dynamically added 'Click' event to an element


I have an HTML list where I set .active class dynamically. Those elements that have this class need to have a 'Click' event that opens MatDialog. The problem is that I'm getting an error when trying to do something like that:

Angular component .html file

<ul>
  <li><span id="asd">asd</span></li>
</ul>

Angular component .ts file

constructor(private el: ElementRef) {}
...
...
this.el.nativeElement.querySelector('#asd').addEventListener('click', this.selectTimeslot);
...
...
selectTimeslot() {
  let asd2: MatDialogRef<CalendarDialogComponent, any> = this.asd.open(CalendarDialogComponent, { disableClose: true });

  asd2.afterClosed().subscribe(result => {
    console.log(`Dialog result: ${result}`);
  });
}

Then when I click an element of the list I'm getting an error:

TypeError: Cannot read property 'open' of undefined

Everything is working fine when I statically declare (click) directive inside HTML like that:

<ul>
  <li><span (click)="selectTimeslot()">asd</span></li>
</ul>

How I can dynamically add a click event to the span element and be able to open the MatDialog component in the Angular 9? Thanks in advance.


Solution

  • I've found a solution myself. This was a classical "this context" problem.

    let self = this;
    ..
    ..
    this.el.nativeElement.querySelector('#asd').addEventListener('click', function() { self.selectTimeslot(this););
    

    At the beginning of the function, I've created a new variable, which points to the context of the Angular component. Then as a parameter, I'm passing the context of the "click event".