Angular 2 - How to add (click) event to dynamically added div

10,505

You should not use jQuery to affect the DOM tree when your application works with Angular2. There is always a way to avoid this kind of the anti-pattern.

If I understand properly, you want to append the div on every click on the element. Why don't you create another component for this? In template, use *ngIf directive in order to show/hide additional content and bind click event to @Component, which will toggle boolean property. Then in parent component just use this component as many as you want. If these child components are specific and needs information, which are available in parent component, just @Input them. If you want to invoke parent component function, you could use @Output in child and then - invoke parent function.

There you can read a lot about this - https://angular.io/docs/ts/latest/cookbook/component-communication.html

Share:
10,505
Amar AttilaZz
Author by

Amar AttilaZz

Updated on June 04, 2022

Comments

  • Amar AttilaZz
    Amar AttilaZz almost 2 years

    I try to append a div into my page via a function in my component like this :

    showTile($event: any,id: number){
           $($event.target).append('<div (click)="somefunction(id)"></div>'))
    }
    
    somefunction(id :number){ console.log(id) }
    

    The div has been appended by somefunction is not handled, in angular js 1.x I used to work with $compile.

  • Amar AttilaZz
    Amar AttilaZz over 7 years
    Ok i will see this option, thank you
  • Günter Zöchbauer
    Günter Zöchbauer over 6 years
    That's statically added, not dynamically, even when *ngIf is used.