Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 12.1 add html element using typescript

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

like image 465
Logwin Finserv Avatar asked Jul 22 '21 12:07

Logwin Finserv


People also ask

How do I add a click event in TypeScript?

To add a click event listener to a button in TypeScript: Select the button element. Use the addEventListener() method to add a click event listener to it. The method will invoke a function every time the button is clicked.

Can you use TypeScript with angular?

TypeScript is a primary language for Angular application development. It is a superset of JavaScript with design-time support for type safety and tooling.


2 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

like image 83
Calummm Avatar answered Oct 07 '22 16:10

Calummm


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

  • Correct way to do DOM Manipulation in Angular 2+
  • https://medium.com/@sardanalokesh/understanding-dom-manipulation-in-angular-2b0016a4ee5d `
like image 45
Robin Dijkhof Avatar answered Oct 07 '22 16:10

Robin Dijkhof