skip to Main Content
getCheckStatus(checkStatus: string) {
    let statusClass = '';
    if (checkStatus === 'Completed') {
      statusClass = 'mat-focus-indicator btn--primary__button mat-raised-button mat-button-base';
    } else {
      statusClass = 'mat-focus-indicator mat-raised-button mat-button-base mat-button-disabled';
    }
    const button = document.createElement('button');
    button.className = statusClass;
    button.textContent = 'Close';
    button.addEventListener("click", () => this.popUp());
    const container = document.createElement('div');
    container.appendChild(button);    
    return container.innerHTML;
  }
popUp() {console.log('Finally this is working');}

I’m trying to call this method by adding addEventListner in my Angular Project. But this is not working, this popUp() method is never called.

MyAssumption: this is a JavaScript code, but we have to write in typescript in Angular, but I can’t find any different syntax especially for typescript.

2

Answers


  1. In an Angular project, you typically don’t use addEventListener directly on DOM elements. Instead, you can use Angular’s event binding to attach methods to DOM events in your component’s template.

    Here’s an example of how you can handle a click event in an Angular component:

    In app.component.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      handleClick() {
        console.log('Button clicked!');
        // Add your logic here
      }
    }
    

    In component.html :

    <button (click)="handleClick()">Click me</button>
    

    Therefore your assumption is wrong. Infact you does not need addEventListener in angular. Refer the above sample to get it in working state.

    Login or Signup to reply.
  2. You can try this:

    button.addEventListener("click", this.popUp.bind(this));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search