Reputation: 1052
I want to bind event with this "tmp", but this attaches also with previous existing button, why?
constructor(private renderer :Renderer ,private element : ElementRef){
}
private appender(){
var tmp = this.renderer.createElement(this.element.nativeElement,'button');
this.renderer.listen(tmp, 'click', ( event:Event ) => console.log(event));
}
Upvotes: 4
Views: 659
Reputation: 41533
This can be achieved using Renderer2
as below,
Injecting the Renderer2 service to the component
constructor(private renderer: Renderer2){}
Register an event listener using listen
method
this.renderer.listen('body', 'click',this.calback)
Call back function will be executed when the event is triggered.
calback(event){
console.log(event)
}
Note: Method definition for listen refer docs for more information
listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any)
Upvotes: 1