I am trying to create a chat-based application where I am creating each type of chat popup according to requirements and using Angular Renderer2
. I tried to add a (click)
attribute to the chat message element while rendering that in UI.
I got this error:
DOMException: Failed to execute 'setAttribute' on 'Element': '((click))' is not a valid attribute name.
chat.component.ts
const btn3: HTMLDivElement = this.renderer.createElement('button');
this.renderer.addClass(btn3, 'btn');
this.renderer.addClass(btn3, 'btn-light');
this.renderer.setAttribute(btn3, '(click)', 'sendMessage()');
btn3.innerHTML = 'Maybe later!';
this.renderer.appendChild(buttons, btn3);
setAttribute
function is to set the element's attributes like disabled
. Instead you could use the listen()
function to add an event listener.
this.renderer.listen(
btn3,
'click',
this.sendMessage.bind(this)
);
OR
this.renderer.listen(
btn3,
'click',
() => this.sendMessage()
);
You either need to bind
or use arrow-functions to preserve the meaning of this
keyword in the callback function.