0

I have the following syntax in the component.ts:

createMap() {
   `const content =` `<div class="text-center">
      <div class="col">
        <p (click)="${open()}">Open</p>
      </div>
    </div>`
}

open() {};

The syntax is assigned to variable and variable is used in Leaflet. I have the open() method in the same component. But the method runs when page loads, and does not work with click.

I also tried open() without ${} but the method is considered as string - no reference.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

2 Answers2

1

This line of code: <p (click)="${open()}">Open</p> is building a string. And ${open()} is the syntax to insert the results of executed code into the string.

So, it runs the code open() and then inserts the results of that function call into the string.

I'm not familiar with the syntax of angular or how you're expected to add an event listener to an element. But I can assure you what you're doing isn't it. You need either a reference to a name of a function, or you need an inline string of javascript to execute, where angular is either providing you with some special component closure, or something like that. Meaning, without Angular you would do:

Actual reference to function:

myParagraphElement.addEventListener('click', open.bind(this))

[OR]

Textual line of javascript to execute:

<p onClick="open()">Click Me</p> // Where open was on the window

I assume the angular syntax you're using with (click) should be a textual line of javascript to execute like <p (click)="open()">Click</p>, and that angular would assume the method is either on the class, or "angular component" with regards to context. But I'm guessing that would only work in whatever "template" HTML you are using, as opposed to just generating a string. But without seeing all of your code, I wouldn't be able to guess.

Cooper Buckingham
  • 2,503
  • 2
  • 15
  • 23
  • Thanks for the explanation. According to this post: https://stackoverflow.com/q/37901436/1009922. It is not possible what I want. – Maihan Nijat Dec 13 '18 at 19:32
  • Your answer should work fine for pure JavaScript but Angular does not allow to use onClick in innerHTML. – Maihan Nijat Dec 13 '18 at 19:33
  • 1
    The `(click)` would be illegal HTML, so I wouldn't go that far. The first 2 examples are for native javascript. The 3rd appears to be valid for angular within a template file, but again, would be meaningless as a native string. – Cooper Buckingham Dec 13 '18 at 19:37
0

bind events to methods like this:

<p (click)="open()">Open</p>

and if you want to extract the event use open($event)

RadekF
  • 476
  • 5
  • 10