5

I have these functions in my index.html of my Angular 2 project:

<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", "teststring");
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    console.log(data);
}
</script>

When I put the functions in my component, it gives the following errors:

Uncaught ReferenceError: drag is not defined at HTMLImageElement.ondragstart
Uncaught ReferenceError: allowDrop is not defined at HTMLDivElement.ondragover

the elements using the functions are in the component html:

<div> ondrop="drop(event)" ondragover="allowDrop(event)">
    <img> src="smiley.png" draggable="true" ondragstart="drag(event)">
</div>

<div ondrop="drop(event)" ondragover="allowDrop(event)">
</div>

5 Answers 5

17

There's no need to move your code to index.html, just do this:

Change

ondrop, ondragover, ondragstart, event

to

(drop), (dragover), (dragstart), $event

respectively in your template(html).

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

2 Comments

This should be accepted answer. This answers the actual question
I agree, I was having the same problem and this answer helped me :)
1

why are you defining in the index.html file?

if you using any functions in the component html you need define these function in the component.ts file.

so move these function into component class

1 Comment

Because they only work in the index.html. They do not work in the component.ts
0

If you are going to use drag and drop frenquently, I recommend you this library: https://www.npmjs.com/package/ng2-dnd

Comments

0

I found a solution on how to implement HTML5 drag and drop in Angular 2: http://www.radzen.com/blog/angular-drag-and-drop/

1 Comment

I've implemented this as well. Have you tried to run your app in a web worker (so your app is not blocking any longer)? See blog.angularindepth.com/…. I'm asking, because it seems not to work in a web worker - unless I made too many errors ;)
-1

Declare a local variable to save data.

For more information see: https://developer.mozilla.org/en-US/docs/Web/Events/drop

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.