Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding: Appending to href

In my Angular 2 test app, I am trying to append an id the following as part of my HTML template:

<a href="https://www.domainname.com/?q="+{{text.id}}>URL</a> 

Not this fails with an error:

(Error: Failed to execute 'setAttribute' on 'Element')

and I am not sure how to append {{text.id}} to this URL.

Do I need to do this in my component, or can it be done somehow inside the HTML template?

BTW, as one would expect, this works just fine (but that's not what I want to do, I need to append text.id to url):

<a href="https://www.domainname.com/?q=">{{text.id}}</a> 

Any suggestions?

like image 874
jjj Avatar asked Oct 31 '16 03:10

jjj


2 Answers

Use either:

<a href="https://www.domainname.com/?q={{text.id}}">URL</a> 

or (from the official docs):

<a [href]="'https://www.domainname.com/?q=' + text.id">URL</a> 



Regarding the question, it's important to notice: The error message is misleading.

When you use {{ expression }}, angular will evaluate the expression and place its value right where the {{}} is. So you don't need to + the result of {{}} to the string as you do. In other words:

<a href="something="+{{ expression }}> WRONG </a>  <a href="something={{ expression }}"> RIGHT </a> <a [href]="'something=' + expression"> RIGHT </a> 
like image 99
acdcjunior Avatar answered Oct 04 '22 15:10

acdcjunior


Alternatively, you can use the following syntax:

[attr.href]="'https://www.domainname.com/?q=' + text.id" 

This might be the preferred way when you want to bind to a variable like

url: string = 'https://www.domainname.com'; 

which would then be bound by

[attr.href]="url" 
like image 39
Kim Kern Avatar answered Oct 04 '22 16:10

Kim Kern