flaviumanica
flaviumanica

Reputation: 195

Links in strings - Typescript

I'm working at a project written in Ionic/Angular/Typescript. In the .html file, I have

< p> {{stringVar}} </p>

In the .ts file,I have

this.stringVar= "Visit http://www.google.com. 
                 Visit http://www.stackoverflow.com."

I have 2 questions:

1) I want the 2 sentences in the string to be displayed in html on different lines. What should I do in order to achieve this: add \n or < br> or something like this?

2) I want the 2 links in the string to appear as links in html,too. That is,when the user clicks on them,he will be taken to those sites.

Thanks in advance!

Upvotes: 1

Views: 22657

Answers (3)

Pardeep Jain
Pardeep Jain

Reputation: 86730

Both Question has one answer you Basically want to Interpolate string with html in the angular, although i am not expert in angular1.x but yes there is one service used for the same called as

 $interpolate(templateString)(you_.ts/js_code);

by using this you can show your string as it as on the webpage event using html in you javascript file too. you just have to pass the html in your string ans display it in the webpage

for example lets assume your use case you simple have to add this like :-

this.stringVar= "Visit <a href='http://www.google.com'>Google</a> Here and<br> Visit <a href='http://www.stackoverflow.com'>Stackoverflow</a> Here."

and than convert this using interpolate like this

$scope.your_string = $interpolate(templateString)(stringVar);

Working Example for the same

Upvotes: 0

Bala
Bala

Reputation: 512

The best approach to go with a 'list', rather than a stringVar

this.linkList = [
    "http://www.google.com",
    "http://www.stackoverflow.com"
];

1) I would suggest to have <p></p> instead of <br/> in between.

2) The following is a working sample with Angular2

<p *ngFor="let link of linkList">Visit <a href="{{link}}">{{link}}</a></p>

Check the working sample here : https://embed.plnkr.co/Om3CXpT9xN07YCz2aHQr/

Upvotes: 0

lmcarreiro
lmcarreiro

Reputation: 5772

1) To appear in different lines, you must put each one inside their own <p> tag, like this:

<p>first line</p>
<p>second line</p>


2) To appear as clickable links, you need to put in <a> tags, with url in href attribute, like this:

<p>click <a href="http://www.google.com/">here</a> to visit google.</p>


It would be better if you could change the structure of your data, to something like this:

<p ng-repeat="url in urlList">Visit <a href="url">{{url}}</a></p>

this.urlList = [
    "http://www.google.com",
    "http://www.stackoverflow.com"
];


or even better:

<p ng-repeat="site in siteList">Visit <a href="site.url">{{site.name}}</a></p>

this.siteList= [
    { name: "Google", url: "http://www.google.com" },
    { name: "StackOverflow", url: "http://www.stackoverflow.com" }
];

Upvotes: 3

Related Questions