2017-05-31 64 views
0

Please find the below code如何綁定<a href>template in angular 2 dynamically?

Component.ts

getReply():string{if(condition){ 
return "The link is: <a href = 'https://www.google.com'>Google</a>"; 
} 

I am binding the above in front end using [innerHtml], using which the above code gets binded and displaying the link, on click which directs to google site.

Whereas, when I try making it dynamically, the link is displayed but not directing to google site.Please find below the way I have tried,

Component.ts

export class ReplyComponent{ 
link : string; 
    getReply():string{if(condition){ 
    this.link = "https://www.google.com"; 
     return "The link is: <a href = 'this.link'>Google</a>"; 
     } 
} 

On trying this, I am able to get the link, but it is not redirecting to google site. Please correct me if I am doing it wrong.

+0

you used "this.link" as a string? try "The link is: Google「; – Val

+2

使用[** template literals **](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals):\'鏈接是:Google \'; – developer033

回答

0

There is a problem in your syntax. The return statement is all string.

return "The link is: <a href = 'this.link'>Google</a>"; 

Here the return statement will return it as a string. To acheive the dynamism change your return value as follows:

return "The link is: <a href = "+this.link+">Google</a>"; 

so that this.link is treated as variable and not as string.