简体   繁体   中英

How to bind <a href>template in angular 2 dynamically?

Please find the below code

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM