简体   繁体   中英

Bind function on click event inside template literal javascript / angular

How can i bind function onclick / (click) inside template literal.

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 .

i have Tried both way vanilla Javascript and in Angular way to bind functions on click events.

Managed it create Dynamic elements with help of @Reyno comment. by using angular's 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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM