0

I'm building an ionic app that lets users chat between each other.

In the event of a user sending a url as plain text, I have a function called urlify that replaces the text with html, and when a user clicks on the html for the url it should take them to that url.

The problem is, anchor elements don't open urls in Ionic, so I have to use window.open(url)..

Here is my code:

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<span class="message-link">' + url + '</span>';
    })
  }
}

openLink(url) {
  window.open(url, '_system')
}

So when a user clicks the span it should open openURL but since I can't add (click)="openURL(url)" to the dynamically generated html, I'm not sure what to do..

Any ideas? Thank you!

isherwood
  • 58,414
  • 16
  • 114
  • 157
Simon
  • 2,498
  • 3
  • 34
  • 77
  • @ABOS because it's user generated text so if someone adds a url as plain text eg https://google.com I need to convert it to a hyperlink so that it's clickable – Simon Jan 23 '19 at 20:16
  • this might help https://stackoverflow.com/questions/48028676/compile-dynamic-html-in-angular-4-5-something-similar-to-compile-in-angular-js – ABOS Jan 23 '19 at 20:23

1 Answers1

0

This can help you, you can add anything dynamically on this way.

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        let newElement = document.createElement('span');
        newElement.innerHTML = url
        newElement.classList.add('message-link');
        newElement.onclick = function() {
            window.open(url, '_system')
        }
        return newElement
    });
  }
}

You can return this newElement or append it here, for example document.getElementById('someDivID').append(newElement) on this way

N.Tasikj
  • 366
  • 1
  • 4