0

I am searching a way to add elements in Angular per Typescript Code. The problem is, that these elements should have a (click) function and I don't know, how many of these elements should be added (for example a for loop with any range should create any amount of elements).

textausgabe.innerHTML += '<div (click)="caller()"'>click</div>';

This created the element correctly, but if I click on it, nothing happens.

Do you know a way to solve my problem, than please show me how :)

0

1 Answer 1

1

You should not do this in angular. Add an array in your ts file and use *ngFor to loop over that array in your template. In your (click) handler you can then just append an element to that array. *ngFor will take care of creating that element for you.

template.html

<div *ngFor="let element of elements" (click)="caller()">click</div>
<button (click)="appendElement()">Append Element</button>

component.ts

@Component({...})
export class MyComponent {
   public elements:Array<unknown> = [];

   public appendElement():void {
      this.elements = [...this.elements, this.elements.length + 1]; // Just append anything, since you are not using the values otherwise, appending a generic ID here
   }

   public caller():void {
      // Do whatever you want when your appended elements are clicked
   }
}

Here a working StackBlitz.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.