Ad

Drag And Drop - How To Get The Actual Html In Dragstart Event And Drop Event

On dragstart event I want to get the actual html of dragged element. But when I do something like this in a dragstart event console.log( e.target); it give me the output like this as expected;

<p style="margin-right:72.45pt; margin-left:50.15pt; text-align:center; font-size:16pt" draggable="true"><strong>CONSULTING AND TECHNICAL SERVICES + (CATS+)</strong></p>

but this code console.log(JSON.stringify(e.target)); give me output like this ;

{"__zone_symbol__dragstartfalse":[{"type":"eventTask","state":"running","source":"HTMLParagraphElement.addEventListener:dragstart","zone":"angular","runCount":2}]}

when send data from dragstart to drop event like this

 e.dataTransfer.setData('Id', e.target);

and then catch data from e.dataTransfer in drop event

 let sourceElement = event.dataTransfer.getData("Id");
    console.log((sourceElement).innerHTML);
    console.log((sourceElement).outerHTML);

I end up with this output [object HTMLParagraphElement] Now , how I convert this [object HTMLParagraphElement] into a presentable HTML on UI as I tried .innerHTML and .outerHTML but it gives me undefined on screen rather proper output.

Ad

Answer

In dragestart event use this

e.dataTransfer.setData('text/html', e.currentTarget.outerHTML); 

Instead of

e.dataTransfer.setData('Id', e.target);

While in drop event you will get the HTML string. Convert that string into an HTML element as follow

  let sourceElement = event.dataTransfer.getData("text/html");
    let doc: any = new DOMParser().parseFromString(sourceElement, "text/html");
    var clonedSourceHtmlElement: HTMLElement = <HTMLElement>(<HTMLElement>doc.firstChild.children[1].children[0]).cloneNode(true);
Ad
source: stackoverflow.com
Ad