簡體   English   中英

在模板文字javascript / angular中的click事件上綁定函數

[英]Bind function on click event inside template literal javascript / angular

如何在模板文字中綁定函數onclick / (click)

例如:

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

在第一個按鈕上是在加載時記錄。 不是點擊。

在第二個按鈕上顯示錯誤: Uncaught ReferenceError: abc is not defined

我已經嘗試過兩種方式 vanilla Javascript 和 Angular 方式來綁定點擊事件上的函數。

在@Reyno 評論的幫助下管理它創建動態元素。 通過使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM