2

I wonder if it is possible to bind a function to a html Template via the template-string notation.

So if i do this

 let dynTamp = `<div> ${device.name} </div>`;

it works perfectly well, but this

let dynTamp = `<button (click)="${someFunction}"></button>`;

does not bind the function to the click event. Am I missing something here?

The Background: I am working with LeafletJs and dynamically create markers on a map, whose popovers should contain buttons:

this.devices.forEach(device => {

        L.marker([Number(device.map_x), Number(device.map_y)], {icon: this.icon})
          .bindPopup(`<h2> ${device.name}</h2>
                  <button (click)="${doThis}"></button>
                  <button (click)="${doThat}"></button>`)
          .addTo(this.map)           
    }
2
  • Yes. An angular expression is not a template string. It's an Angular expression. The syntax to call someFunction() when a button is clicked is (click)="someFunction()". And Angular templates need to be compiled. You can't just dynamically generate HTML containing Angular markup and hope it works. It won't. Commented Aug 13, 2018 at 15:50
  • Well sure, we know that from AngularJS. In my first example though it does get compiled, that why I wondererd if there was a way to so so with functions also Commented Aug 14, 2018 at 5:43

2 Answers 2

2

This should be the correct syntax :

let dynTamp = `<button (click)="someFunction()"></button>`;

I share an example of how to use a template string : View Example

Sign up to request clarification or add additional context in comments.

3 Comments

If I do so, the function does not get called on click
in which life cycle are you declaring "dynMap" ??
A I see, thank you! The difference is, that you use the String as a regular Angular Template, whereas I create the Template dynamically and add it to the Dom - after it`s compiled. That is why this works for you, but unfortunately not in my case.
0

please replace with this

let dynTamp = `<button (click)="someFunction()"></button>`;

instead of

let dynTamp = `<button (click)="${someFunction}"></button>`;

An angular expression is not a template string. It's an Angular expression. The syntax to call someFunction() when a button is clicked is (click)="someFunction()".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.