1

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.

Najam Us Saqib
  • 3,190
  • 1
  • 24
  • 43
  • 2
    I'd suggest using [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) instead of assigning click events to each element. – Reyno May 16 '22 at 12:42
  • Does `(click)="abc(${locations[i])}"` work? Also, you can use ngFor and move this logic to the .html file itself instead of creating this in js – adiga May 16 '22 at 12:44
  • You tagged this angular so why are you doing it this way in an angular app? – epascarello May 16 '22 at 12:46
  • @adiga no this is not working. No i can't use it with `*ngFor` because i am Binding this html as popup to markers on Map. – Najam Us Saqib May 16 '22 at 12:52
  • @epascarello i am using angular and i tried it in angular way but its not working so it tried it that way. – Najam Us Saqib May 16 '22 at 12:53
  • What does the angular code look like? – epascarello May 16 '22 at 12:54
  • Please post complete code. There is not enough here to answer the question. https://stackoverflow.com/help/how-to-ask –  May 16 '22 at 13:25

1 Answers1

0

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;
 }
Najam Us Saqib
  • 3,190
  • 1
  • 24
  • 43