0

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);

enter image description here

1 Answer 1

2

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.

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

1 Comment

Thanks @michael-d for helping, Regards, Bharat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.