[英]Set (click) attribute in button using renderer2 in Angular
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
.我正在尝试创建一个基于聊天的应用程序,在其中我根据要求创建每种类型的聊天弹出窗口并使用
Angular Renderer2
。 I tried to add a (click)
attribute to the chat message element while rendering that in UI.我尝试在 UI 中呈现聊天消息元素时向聊天消息元素添加
(click)
属性。
I got this error:我收到了这个错误:
DOMException: Failed to execute 'setAttribute' on 'Element': '((click))' is not a valid attribute name.
DOMException:无法在“元素”上执行“setAttribute”:“((单击))”不是有效的属性名称。
chat.component.ts聊天组件.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
. setAttribute
function 是设置元素的属性,如disabled
。 Instead you could use the listen()
function to add an event listener.相反,您可以使用
listen()
function 添加事件侦听器。
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.您需要
bind
或使用箭头函数在回调 function 中保留this
关键字的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.