简体   繁体   English

如何<a href>动态</a>绑定<a href>角度2中的模板?</a>

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

Please find the below code 请找到下面的代码

Component.ts 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. 我在前端使用[innerHtml]绑定上述内容,使用该代码绑定上面的代码并在指向Google网站的点击时显示链接。

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, 而当我尝试动态创建链接时,该链接会显示但未定向到Google网站。请在我尝试的方法下方找到,

Component.ts 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. 尝试此操作后,我能够获得链接,但是它没有重定向到Google网站。 Please correct me if I am doing it wrong. 如果我做错了,请纠正我。

There is a problem in your syntax. 您的语法有问题。 The return statement is all string. return语句全为字符串。

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

Here the return statement will return it as a string. 在这里,return语句将其作为字符串返回。 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. 因此this.link被视为变量而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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