Angular 2 - How to add (click) event to dynamically added div
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
Amar AttilaZz
Updated on June 04, 2022Comments
-
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 over 7 yearsOk i will see this option, thank you
-
Günter Zöchbauer over 6 yearsThat's statically added, not dynamically, even when
*ngIf
is used.