[英]Bind function on click event inside template literal javascript / angular
How can i bind function onclick / (click)
inside template literal.如何在模板文字中绑定函数
onclick / (click)
。
For Example:例如:
for (let i = 0; i < locations.length; i++) {
let customHtml = `
<div class="flex">
<ion-button size="small" (click)="${abc(locations[i])}">Message</ion-button>
<ion-button size="small" onclick="abc('${locations[i]}')">Request</ion-button>
</div>
`;
}
abc(l){
console.log(l);
}
on 1st button is it getting logged at the time of loading.在第一个按钮上是在加载时记录。 Not on clicking.
不是点击。
on 2nd button it is showing error: Uncaught ReferenceError: abc is not defined
.在第二个按钮上显示错误:
Uncaught ReferenceError: abc is not defined
。
i have Tried both way vanilla Javascript and in Angular way to bind functions on click events.我已经尝试过两种方式 vanilla Javascript 和 Angular 方式来绑定点击事件上的函数。
Managed it create Dynamic elements with help of @Reyno comment.在@Reyno 评论的帮助下管理它创建动态元素。 by using angular's
Renderer2
.通过使用 Angular 的
Renderer2
。
for (let i = 0; i < locations.length; i++) {
let customHtml = this.addCustomHtml(locations[i]);
// can use it here it is working now.
}
addCustomHtml(l) {
const p1 = this.renderer.createElement('p');
const p1Text = this.renderer.createText(`ID: ${l[0]}`);
this.renderer.appendChild(p1, p1Text);
const p2 = this.renderer.createElement('p');
const p2Text = this.renderer.createText(`Lat: ${l[1]} \n Lng: ${l[2]}`);
this.renderer.appendChild(p2, p2Text);
const button = this.renderer.createElement('ion-button');
const buttonText = this.renderer.createText('Send Request');
button.size = 'small';
button.fill = 'outline';
button.onclick = function () {
console.log(l);
};
this.renderer.appendChild(button, buttonText);
const container = this.renderer.createElement('div');
this.renderer.appendChild(container, p1);
this.renderer.appendChild(container, p2);
this.renderer.appendChild(container, button);
return container;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.