1

In my angular component,

  <div contentEditable="true"  id="mytext" ></div>
  <button type="button" (click)="goSee()">SEE ME !</button>  

In class,there is goSee() method because I want to change selected text(later url) to a real clickable href.

goSee()
     {
  var startIndex = window.getSelection().getRangeAt(0).startOffset;
  var endIndex = window.getSelection().getRangeAt(0).endOffset;
  var slicedText = document.getElementById("mytext").innerText.slice(startIndex, endIndex);
   document.getElementById("mytext").innerHTML.anchor(slicedText);

    }

Entering url to "mytext" and selectedText works,,But NO hyperlink and clickable link appears .... Please Suggest me and Thank you all in advance..

KyiLis
  • 91
  • 1
  • 7

1 Answers1

2

First, you have to use link method to create anchor with the href attribute. Second, innerHTML is a property and you have to set it. Assuming that slicedText is a url you want to put into href attribute, you can achieve what you're trying to do like this:

var existingLinkText = document.getElementById("mytext").innerHTML;
document.getElementById("mytext").innerHTML = existingLinkText.link(slicedText);

Also, if your template is part of the component's template, I would suggest to use ElementRef to get access to the DOM instead of global document.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • It works and display likes a hyperlink !! But when slicedText is url like 'www.google.com' ,it goes 'www.google.com' from my prj like 'localhost:8080/Prj/www.google.com' ..Doesnt go just 'www.google.com' ! – KyiLis Nov 23 '16 at 16:11
  • 1
    this is a different question. you need to have a `href` starting with `http://` for you browser to treat it like a link to a different resoure, rather than a relative link. you can mark this answer as accepted if it answers your question and ask another question for specific details of your second question. put a link to the other question here. – Max Koretskyi Nov 23 '16 at 16:27
  • 1
    but before read [this](http://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/) and [this](http://stackoverflow.com/a/21828923/2545680) – Max Koretskyi Nov 23 '16 at 16:29
  • Thank you Maximus .. I realize more of href .. : ) – KyiLis Nov 23 '16 at 16:43