如何绑定<a href="">template in angular 2 dynamically?

时间:2017-05-31 03:07:13

标签: angular

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.

1 个答案:

答案 0 :(得分:0)

您的语法有问题。 return语句都是字符串。

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

这里的return语句将它作为字符串返回。为了实现动力,请按以下方式更改您的返回值:

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

这样this.link被视为变量而不是字符串。