Angular 12.1 add html element using typescript

Viewed 2236

I'm learning angular via youtube, but I'm trying to do something new, and I'm getting an error on that, my code is attached below, help me out.

I want to setAttribute like this div.setAttribute('(click)',"popUp($event)"); but I got error.

TypeScript

export class AppComponent {
    createEl(){
      console.time("timer");
      for (let i = 0; i < 10; i++) {
        let div = document.createElement("div");
        div.textContent = `Hello, World! ${i}`;
        div.setAttribute('(click)',"popUp($event)");
        document.getElementById('divEl')?.appendChild(div);
      };
      console.timeEnd("timer");
}

HTML

<div id="divEl"></div>
<button (click)="createEl()">click me</button>

Error

my Error photo

6 Answers

This is not really the angular way of doing things. Try to avoid operations on document such as document.createElement.

A better way to achieve this would be to define what the repeating element would look like in the template and drive it from an array. That way we can keep the template doing display and the typescript doing processing, and Angular handling everything in between.

HTML

<div id="divEl">
  <div *ngFor="let row of rows; index as i;" (click)="popUp($event)">
    Hello, World! {{i}}
  </div>
</div>

<button (click)="createEl()">click me</button>

Typescript

export class AppComponent {
  rows: unknown[] = [];
  createEl():void {
    this.rows.push('something');
  }

  popUp(event:Event):void {}
}  

More reading on loops: https://angular.io/api/common/NgForOf

That's right check below.

div.addEventListener('click', (e) => {
  this.popUp(e);
});

Problem is you are trying to do angular stuff with pure javascript.

<div (click)="method()"> is angular. In javascript you'd do someting like this <button onclick="myFunction()">Click me</button> Other options are to use event handlers https://www.w3schools.com/js/js_htmldom_eventlistener.asp

Anyhow, angular doesn't recommend changes the DOM because then it won't recognize those changes. Here are multiple examples ho to properly change the dom

You can set the click event as shown below instead of using setAttribute

div.addEventListener('click', (e) => {
  this.popUp(e);
});

(click) is not an html attribute, it is Angular event binding syntax

This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right.

You cannot use that with JavaScript. Use

div.onclick = popUp;
export class AppComponent {
    createEl(){
      console.time("timer");
      for (let i = 0; i < 10; i++) {
        let div = document.createElement("div");
        div.textContent = `Hello, World! ${i}`;

        div.addEventListener('click', (e) => {
          this.popUp(e);
        });

        document.getElementById('divEl')?.appendChild(div);
      };
      console.timeEnd("timer");
}
Related